`

interrupt

阅读更多

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!

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics