1. 程式人生 > >調用Thread.interrupt()方法到底會發生什麽?

調用Thread.interrupt()方法到底會發生什麽?

less ted which live bsp set med run status

1. 當線程處於Blocked狀態(sleep,wait,join),線程會退出阻塞狀態,並拋出一個InterruptedException。park除外,它有響應但是不會拋出異常

2. 當線程處於Running狀態,只是線程的interrupt標記被設置為true,線程本身的運行不會受到任何影響。

上面說得其實還不是特別準確,Java 1.8的Thread.interrupt()方法的註釋如下,這個應該是最為權威準確的

Unless the current thread is interrupting itself, which is always permitted, the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.
If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.
If this thread is blocked in an I/O operation upon an InterruptibleChannel then the channel will be closed, the thread‘s interrupt status will be set, and the thread will receive a java.nio.channels.ClosedByInterruptException.
If this thread is blocked in a java.nio.channels.Selector then the thread‘s interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector‘s wakeup method were invoked.
If none of the previous conditions hold then this thread‘s interrupt status will be set.
Interrupting a thread that is not alive need not have any effect.

調用Thread.interrupt()方法到底會發生什麽?