美文网首页
java中线程中断interrupt

java中线程中断interrupt

作者: ppyy_power | 来源:发表于2019-01-28 15:36 被阅读0次

    java中涉及线程中断主要有3个方法

    1.interrupt(),在一个线程中调用另一个线程的interrupt()方法,即会向那个线程发出信号——线程中断状态已被设置。至于那个线程何去何从,由具体的代码实现决定。
    2.isInterrupted(),用来判断当前线程的中断状态(true or false),不会清除线程的中断状态。
    3.interrupted()是个Thread的static方法,也会判断线程的中断状态,但是会清除线程的中断状态。

    /**
         * Tests whether the current thread has been interrupted.  The
         * <i>interrupted status</i> of the thread is cleared by this method.  In
         * other words, if this method were to be called twice in succession, the
         * second call would return false (unless the current thread were
         * interrupted again, after the first call had cleared its interrupted
         * status and before the second call had examined it).
         *
         * <p>A thread interruption ignored because a thread was not alive
         * at the time of the interrupt will be reflected by this method
         * returning false.
         *
         * @return  <code>true</code> if the current thread has been interrupted;
         *          <code>false</code> otherwise.
         * @see #isInterrupted()
         * @revised 6.0
         */
        public static boolean interrupted() {
            return currentThread().isInterrupted(true);
        }
    

    interrupt只是改变线程的中断状态,状态改变以后的具体逻辑还需要由代码来实现,另外的重要作用就是将等待中的线程解救出来,抛出InterruptedException,任何抛出InterruptedException异常的方法都可以使用interrupt()方法。

    public class InterruptionInJava implements Runnable{
        private volatile static boolean on = false;
        public static void main(String[] args) throws InterruptedException {
            Thread testThread = new Thread(new InterruptionInJava(),"InterruptionInJava");
            //start thread
            testThread.start();
            Thread.sleep(1000);
            InterruptionInJava.on = true;
            testThread.interrupt();
     
            System.out.println("main end");
     
        }
     
        @Override
        public void run() {
            while(!on){
                try {
                    Thread.sleep(10000000);
                } catch (InterruptedException e) {
                    System.out.println("caught exception right now: "+e);
                }
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:java中线程中断interrupt

          本文链接:https://www.haomeiwen.com/subject/rumajqtx.html