java之interrupt中斷線程

java中線程在運行過程當中能夠經過interrupt方法進行中斷,這裏須要提到幾個的注意點:java

一、中斷狀態是能夠被清除或者說恢復的
二、中斷請求不是必定會被響應(如io包中的一些操做,只會標記中斷狀態,而對線程並無實際影響)
三、調用interrupt並非當即中斷線程執行,而是傳遞了中斷請求

下面看demoide

public class MyInterrupt implements Runnable{


    private volatile int i = 0;
    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {

            System.out.println(i++ + String.valueOf(Thread.currentThread().isInterrupted()));
            
            //Point1:若是在這裏調用中斷請求,程序會在i=20時拋出異常,但不會中斷,線程繼續執行下去
            //if (i == 20) {
            //    cancel();
            //}
            try {
                Thread.sleep(100);
                //this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();

            }
            //Point2:在此處調用中斷請求,最後打印 19:false  isInterrupted()返回true因此不在進入循環體
            if (i == 20) {
                cancel();
            }

        }
    }

    public void cancel(){
        Thread.currentThread().interrupt();
    }

    public static void main(String[] args) {
        new Thread(new MyInterrupt()).start();
    }
}

在point1處去中斷時候爲何程序會繼續執行,這裏咱們看下sleep方法以及wait方法的docthis

/**
     * Causes the currently executing thread to sleep (temporarily cease
     * execution) for the specified number of milliseconds, subject to
     * the precision and accuracy of system timers and schedulers. The thread
     * does not lose ownership of any monitors.
     *
     * @param  millis
     *         the length of time to sleep in milliseconds
     *
     * @throws  IllegalArgumentException
     *          if the value of {@code millis} is negative
     *
     * @throws  InterruptedException
     *          if any thread has interrupted the current thread. The
     *          <i>interrupted status</i> of the current thread is
     *          cleared when this exception is thrown.
     */
    public static native void sleep(long millis) throws InterruptedException;

在jdk8中的註釋中咱們能夠發現@throws中說明了,若是任意線程發出了中斷請求,當拋出InterruptedException異常後,中斷狀態會被清除,也就是說該線程不會被中斷,再次調用isInterrupted方法則會返回false。線程

相關文章
相關標籤/搜索