1) Each thread has a boolean interrupted status.
2) 3 interrupt related methods defined in Thread class
public class Thread
{
public void interrupt() {...} // interrupts the target thread
public boolean isInterrupted() {...} //return the interrupted status of the target thread.
//clear the interrupted status of the current thread, and returns its previous value.
//This is the 1st way to clear the interrupted status
public static boolean interrupted() {...}
}
3) Another way the clear the interrupted status is:
When the thread is in blocked status, if you call interrupt() on it, the thread will automatically go to Catch(InterruptedException e){...} block. As soon as the exception is thrown out, the interrupted status will be cleared.
4) interrupt() method acutally does just one thing --- set interrupted status to true. Nothing else. From this point of view, it only makes sense when the thread is monitoring the interrupted status.
The thread will monitor the interrupted status only under 1 situation --- the thread is in blocked status which is wrapped with catch(InterruptedException e){}
1) thread.sleeping()
2) object.waiting()
3) BlockedQueue operations
4) Lock.lockInteruptibly()
What I want to say is, very likely, interrupt() method doesn't work for some thread, it means those threads are not interruptable.
So, just one sentence to summary,
If the current line of code is monitored by InterruptedException, then, if you interrupt it at the time or before that, it will work. Otherwise, just everthing in vain---setting interrupted status to true means nothing!
本文详细解析了Java中线程中断的实现机制,包括如何设置线程的中断状态、检查线程是否被中断以及几种典型的阻塞操作如何响应中断信号。通过具体的代码示例,阐述了线程中断的有效场景及其限制。
1656

被折叠的 条评论
为什么被折叠?



