Stop a Java thread from executing

Source: Internet
Author: User

Find a way to stop the thread from running, the code is as follows:

 Public classStopthreadextendsThread {Private volatile BooleanStop =false; @Override Public voidrun () {System.out.println ("T1 is start ...");  while(!stop) {System.out.println ("T1 is running ...."); } System.out.println ("T1 stopped"); }         Public voidTerminate () {Stop=true; }         Public Static voidMain (string[] args) {stopthread T1=NewStopthread ();        T1.start ();  for(inti = 0; I < 500000;i++) {System.out.println ("Main is running ....");    } t1.terminate (); }}

You can then stop the thread that is running.

But there's a problem with that, and what I'm writing now is that I'm going to go back to the while and judge the condition so that it jumps out. However, if you want to control the thread execution time, if the timeout is not executed, return directly, this code is still inappropriate. Can think again ....

Stop a Java thread from executing

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.