From: http://jay-kid.iteye.com/blog/557064
In Java Network Programming, we can see an example that thread. Interrupt () is used to close the waiting thread. I don't quite understand, so I checked the Java API.
If you are interested, you can first look at the API content and then look at the following summary:
1. Both thread. isinterrupt () and thread. interrupted () return the status of the current thread interrupt.
- Thread. isinterrupt () is a non-static function with the goal of "thread instance". Its general usage is as follows,
Java code
- Testinterrupt T = new testinterrupt ();
- T. Start ();
- System. Out. println (T. isinterrupt ());
- Thread. interrupted () is a static function with the goal of "current thread"
Java code
- System. Out. println (thread. interrupted ());
In addition, it will "reset" the interrupt status of the current thread. If the isinterrupt status of the current thread is set to true, it will return true, but then the isinterrupt status will be reset to false. Call (thread) T. isinterrupt or thread. interrupted will return false
2. There are several possibilities after interrupt () is called:
When the thread is blocked:
- If the thread is calling
Object
Classwait()
,wait(long)
Orwait(long, int)
Method, orjoin()
,join(long)
,join(long, int)
,sleep(long)
Orsleep(long, int)
If the isinterrupt status is cleared and set to false, the isinterruptedexception is also received.
Java code
- Public void run (){
- While (! Thread. currentthread (). isinterrupted ()){
- Try {
- Thread. Sleep (1000 );
- } Catch (interruptedexception IE ){
- Ie. printstacktrace ();
- }
- }
- }
As shown above, if the thread runs to the thread. when sleep (1000) is used, the interrupt () method of the thread is called by other threads. It will enter the catch section and then run while (! Thread. currentthread (). isinterrupted () Exits run and the thread is destroyed.
- If the thread is blocked in I/O operations on the interrupted channel, the channel will be closed and the isinterrupt status of the thread will be set to true, and the thread will receive
ClosedByInterruptException
.
When the thread runs normally:
- This thread is not affected and continues to run, but the isinterrupt status of this thread will be set to true
Java code
- Public void run (){
- While (! Thread. currentthread (). isinterrupted ()){
- Try {
- // A: no blocking code .......
- ......
- // B: interrupt .......
- ......
- // C: no blocking code .......
- } Catch (interruptedexception IE ){
- Ie. printstacktrace ();
- }
- }
- }
As shown above, when the thread runs normally and is called interrupt () when it runs to point B, the thread continues to run normally, but the isinterrupt status is set to true, after completing the code for A, B, and C, go to the while (! Thread. currentthread (). isinterrupted (), the thread is destroyed. If the while check condition is changed to (true), the thread will not be affected and will continue to run.