How to interrupt a thread in Java

Source: Internet
Author: User

How to interrupt the Java thread? Check the API. Isn't the interrupt () method used? If the Thread has been interrupted, Use Thread. currentThread (). isInterrupted () to return true/false: public class ThreadDemo extends Thread {
Public static void main (String [] args) throws InterruptedException {
Thread thread = new ThreadDemo ();
Thread. start ();
Thread. sleep (100 );
Thread. interrupt (); // interrupt thread
}

@ Override
Public void run (){
While (! Thread. currentThread (). isInterrupted ()){
System. out. println ("thread running ");

Try {
Thread. sleep (100 );
} Catch (InterruptedException e)
{
System. out. println ("InterruptedException ");
}
}

System. out. println ("thread interrupted ");
}
} Running result:
Thread running
InterruptedException
Thread running
Thread running
Thread running
Thread running
... Soon I found that this method seemed to have a problem and the Thread was not interrupted successfully. So I called break to jump out of the while loop after handling the InterruptedException exception: public class ThreadDemo extends Thread {
Public static void main (String [] args) throws InterruptedException {
Thread thread = new ThreadDemo ();
Thread. start ();
Thread. sleep (100 );
Thread. interrupt (); // interrupt thread
}

@ Override
Public void run (){
While (! Thread. currentThread (). isInterrupted ()){
System. out. println ("thread running ");

Try {
Thread. sleep (100 );
} Catch (InterruptedException e)
{
System. out. println ("InterruptedException ");
Break;
}
}

System. out. println ("thread interrupted ");
}
} Successful thread interruption in running result ):
Thread running
InterruptedException
Thread interrupted went on to search for it on the Internet. After writing some examples, I learned how to write an interrupted thread.
First, it is found that after the start () of the call Thread, the interrupt () Thread is called to interrupt the Thread immediately, and the Thread is stopped. The Thread is blocked outside the while condition: public class ThreadDemo extends Thread {
Public static void main (String [] args) throws InterruptedException {
Thread thread = new ThreadDemo ();
Thread. start ();
// Thread. sleep (100 );
Thread. interrupt (); // interrupt thread
}

@ Override
Public void run (){
System. out. println ("in run ()");
While (! Thread. currentThread (). isInterrupted ()){
System. out. println ("thread running ");

Try {
Thread. sleep (100 );
} Catch (InterruptedException e)
{
System. out. println ("InterruptedException ");
// Break;
}
}

System. out. println ("thread interrupted ");
}
} Running result:
In run ()
Thread interrupted is then interrupted again during exception handling according to the Internet. In this way, the Thread can be successfully interrupted using the interrupt method: public class ThreadDemo extends thread {
Public static void main (String [] args) throws InterruptedException {
Thread thread = new ThreadDemo ();
Thread. start ();
Thread. sleep (100 );
Thread. interrupt (); // interrupt thread
}

@ Override
Public void run (){
While (! Thread. currentThread (). isInterrupted ()){
System. out. println ("thread running ");

Try {
Thread. sleep (100 );
} Catch (InterruptedException e)
{
System. out. println ("InterruptedException ");
Thread. currentThread (). interrupt (); // Thread is interrupted again
// Break;
}
}

System. out. println ("thread interrupted ");
}
} Successful thread interruption in running result ):
Thread running
InterruptedException
Why does thread interrupted add sleep () before calling interrupt (), resulting in different results?
In my opinion, the Thread object is allocated to the Resource Creation Thread for CPU scheduling only when start () is called. This process takes time. Because of the time difference, the interruption mark has been set on before entering the run () method, so it is blocked on the while condition.
The thread is interrupted again, the interrupt mark is set on, and then the loop returns to the while condition judgment, so the loop is exited.
After the thread is interrupted, the object still exists, but the thread cannot call start () Again. Otherwise, an exception IllegalThreadStateException is reported. Public class ThreadDemo extends Thread {
Public static void main (String [] args ){
Try {
ThreadDemo thread = new ThreadDemo ();
Thread. start ();
Thread. sleep (100 );

Thread. interrupt (); // interrupt thread
Thread. sleep (100 );

Thread. printStr ();
Thread. interrupt (); // The third thread to interrupt

Thread. printStr ();
Thread. join ();
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}

Private void printStr (){
System. out. println ("thread obj ");
}

@ Override
Public void run (){
While (! Thread. currentThread (). isInterrupted ()){
System. out. println ("thread running ");

Try {
Thread. sleep (100 );
} Catch (InterruptedException e)
{
System. out. println ("InterruptedException ");
Thread. currentThread (). interrupt (); // Thread is interrupted again
}
}

System. out. println ("thread interrupted ");
}
} Running result:
Thread running
InterruptedException
Thread interrupted
Thread obj
Thread objSummary:
1. Call interrupt () immediately after the thread starts (). The interrupt mark is already set on when it enters run;
2. When processing the InterruptedException that sleep () may throw, the thread can be interrupted again;
3. Note that the interrupt () method is set on interrupt mark, and the interrupted () method is used to determine and clear the interrupt mark.
 Differences between isInterrupted () and interrputed () Methods
Public static boolean interrupted ()
Test whether the current thread has been interrupted. This method clears the thread interruption status. In other words, if this method is called twice in a row, false is returned for the second call. After the first call is cleared, and the second call is completed, except when the current thread is interrupted again ). Public boolean isInterrupted ()
Test whether the thread has been interrupted. The thread interruption status is not affected by this method. Both are true if the thread has been interrupted; otherwise, false is returned. Refer to the article Java thread can interrupt http://blog.csdn.net/sapphiron/archive/2008/10/05/3018053.aspx this article introduces more methods to deal with the interruption of other blocking situations.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.