Java example of a method that ends the run stop thread through a shared variable _java

Source: Internet
Author: User
Tags exception handling

The Stop () method has been deprecated because it is not safe. Detailed explanations are given in the API documentation.
Interrupts the thread through the interrupted () method. Not recommended.
Stop the thread by ending the run () method with a shared variable. such as instance

Copy Code code as follows:

public class Threadinterrupt {
public static void Main (String []args) {
Runner run = new Runner ();
Run.start ();
try {
Thread.Sleep (10000);
catch (Interruptedexception e) {
TODO auto-generated Catch block

}

Run.stop ()//obsolete methods, not recommended, too rough
Run.interrupt (); Throws an exception, but it is obviously inappropriate to write a business in exception handling and is not recommended
run.flag=false;//recommended method for stopping a thread
}
}

Class Runner extends thread{
Boolean flag = true;
public void Run () {
/* while (true) {
System.out.println (New Date () + "----");
try {
Sleep (1000);
catch (Interruptedexception e) {
TODO auto-generated Catch block
System.out.println ("interrupted");
Return
}
}
*/

while (flag) {
System.out.println (New Date () + "----");
try {
Sleep (1000);
catch (Interruptedexception e) {
TODO auto-generated Catch block
System.out.println ("interrupted");
Return
}
}
}
}

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.