interrupt()和interrupted
阿新 • • 發佈:2018-11-11
- 1.interrupt()
interrupt()的作用是中斷本執行緒。
本執行緒中斷自己是被允許的;其它執行緒呼叫本執行緒的interrupt()方法時,會通過checkAccess()檢查許可權。這有可能丟擲SecurityException異常。
如果本執行緒是處於阻塞狀態:呼叫執行緒的wait(), wait(long)或wait(long, int)會讓它進入等待(阻塞)狀態,或者呼叫執行緒的join(), join(long), join(long, int), sleep(long), sleep(long, int)也會讓它進入阻塞狀態。
若執行緒在阻塞狀態時,呼叫了它的interrupt()方法,那麼它的“中斷狀態”會被清除並且會收到一個InterruptedException異常。例如,執行緒通過wait()進入阻塞狀態,此時通過interrupt()中斷該執行緒;呼叫interrupt()會立即將執行緒的中斷標記設為“true”,但是由於執行緒處於阻塞狀態,所以該“中斷標記”會立即被清除為“false”,同時,會產生一個InterruptedException的異常。
如果執行緒被阻塞在一個Selector選擇器中,那麼通過interrupt()中斷它時;執行緒的中斷標記會被設定為true,並且它會立即從選擇操作中返回。
如果不屬於前面所說的情況,那麼通過interrupt()中斷執行緒時,它的中斷標記會被設定為“true”。
中斷一個“已終止的執行緒”不會產生任何操作。
這裡只舉例sleep 上述其他方法也是同樣效果:
public class InterruptTest { public static void main(String[] args) { System.out.println(Thread.currentThread().getName()+" interrupt before "+Thread.currentThread().isInterrupted()); Thread.currentThread().interrupt(); System.out.println(Thread.currentThread().getName()+" interrupt after "+Thread.currentThread().isInterrupted()); } }
結果:
main interrupt before false
main interrupt after true
class TestThread extends Thread { public TestThread(String name){ setName(name); } public void run() { try{ Thread.sleep(10); }catch(Exception e){ e.printStackTrace(); } } } public class InterruptTest { public static void main(String[] args) throws InterruptedException { TestThread tt = new TestThread("test"); tt.start(); System.out.println(tt.getName()+" interrupt before "+tt.isInterrupted()); tt.interrupt();//中斷sleep將會清空中斷狀態 Thread.sleep(1000);//等待test執行緒 System.out.println(tt.getName()+" interrupt after "+tt.isInterrupted()); } }
結果:
test interrupt before false
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at thread2.TestThread.run(InterruptTest.java:11)
test interrupt after false
- 2.interrupted
測試當前執行緒是否中斷,這個方法將會清除中斷狀態,換句話說,如果這個方法被成功呼叫2次,第二次將會返回false,除非當前執行緒再次被中斷,可以在第一個呼叫後,第二次呼叫前去檢測它。
public class InterruptTest
{
public static void main(String[] args) throws InterruptedException
{
System.out.println(Thread.currentThread().getName()+" interrupt before "+Thread.currentThread().interrupted());
Thread.currentThread().interrupt();
System.out.println(Thread.currentThread().getName()+" interrupt after once "+Thread.currentThread().interrupted());//呼叫之後清除中斷狀態
System.out.println(Thread.currentThread().getName()+" interrupt after twice "+Thread.currentThread().interrupted());
}
}
結果:
main interrupt before false
main interrupt after once true
main interrupt after twice false