Java thread stop

Source: Internet
Author: User

</BR>

 

Class student implements runnable {public Boolean flag = true;/* Public void run () {While (FLAG) {system. out. println (thread. currentthread (). getname () ;}} */Public synchronized void run () {While (FLAG) {try {Wait (); system. out. println (thread. currentthread (). getname ();} catch (exception ex) {system. out. println (thread. currentthread (). getname () + "....... exception "); flag = false ;}}} public class stopthread {public static void main (string ARGs []) {student Stu = new student (); thread T1 = new thread (Stu); thread t2 = new thread (Stu); t1.start (); t2.start (); For (INT I = 0; I <100; I ++) {system. out. println (thread. currentthread (). getname (); Stu. flag = false; t1.interrupt (); t2.interrupt () ;}}/** thread stop * in multithreading, threads are generally executed cyclically, the Code executed in the thread is the code defined in the run method. If the run function ends, the thread ends naturally * so the end of the control thread is to control the end of the loop in the run method, that is to say, you can set the thread running switch *** at a certain time. However, when the thread is out of the wait status, although you have changed the status, it is now in the wait status, if it cannot end now, use another method in the thread: interrupt, * interrupt will clear the wait sleep state, then run the program, and an interruptexception will be thrown, therefore, you can set the Run switch in the catch exception, and * if there is no wait in this method, the thread will not be stopped. ** therefore, we can conclude from the above two points that there are two points to terminate the process, first, set the thread running switch at a certain time point, and use interrupt if wait exists, and then catch exceptions, set the thread running switch in the exception * ** 20:49:21 **/

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.