Logically stop one thread in Java

Source: Internet
Author: User

1, the first is also the most common one is the use of State bits

public class Task extends Thread {

Private volatile Boolean flag= true;

public void Stoptask () {

Flag = false;

}

@Override

public void Run () {

while (flag) {

/* Do your no-block task */

}

}

}

This is the most classic way to safely terminate the current thread, the structure is simple refining, recommended to use. But this is also flawed, and there is no way to terminate a thread when the execution of a while loop, such as IO, is timed out.


2. Terminating a thread by using the Stop method

Use the Stop method to forcibly terminate a running or suspended thread. We can use the following code to terminate the thread:

Thread.stop ();

Although using the above code can terminate a thread, using the Stop method is dangerous, just like suddenly shutting down the computer, rather than shutting down as a normal program, it is not recommended to use the Stop method to terminate the thread.


3. Terminating a thread using the interrupt method

Using the interrupt method to end a thread can be divided into two situations:

(1) The thread is in a blocked state, such as using the Sleep method.

(2) Use while (! Isinterrupted ()) {...} To determine if a thread has been interrupted.

In the first case, using the interrupt method, the sleep method throws a Interruptedexception exception, and in the second case the thread exits directly.


Logically stop one thread in Java

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.