Stop running a thread in Executorservice

Source: Internet
Author: User

1  while(true){2                     Try {    3Sleep (1000);4}Catch(interruptedexception e) {5                         //TODO auto-generated Catch block6 e.printstacktrace ();7                     }8}

Like the code above, the thread does not stop using the Executorservice object to call the Shutdownnow method or the Shutdown method. To stop the thread, you need to change to the following code:

1  while(!thread.interrupted ()) {2 3                     4 5                 Try {6Sleep (1000);7}Catch(interruptedexception e) {8 e.printstacktrace ();9                     //End LoopTen  Thread.CurrentThread (). interrupt ();  One}

The difference between the Shutdownnow method and the Shutdown method:

1, Shutdown method: This method, can only immediately interrupt those who currently have no task, in the waiting state from Blockingqueue to get the task exception. You cannot interrupt the thread that is in the execution of the task, or the thread that is suspended during the execution of the task.

2, Shutdownnow method: Regardless of whether the task is in the execution, all interrupt, not to judge what locks do not lock.

Stop running a thread in Executorservice

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.