Thread's life cycle, thread end

Source: Internet
Author: User
Tags thread stop

A new thread enters the running state through Start (), and the yield () method can be used for comity in the running state, but it can still be done, and if the field needs to be paused now, it can be suspend (),

Sleep (), wait () method. If the thread does not execute, it can be ended by ending with a stop () (if the run () method finishes executing) or a new thread calling stop () directly.

Suspend (): Pending.

Resume (): Resumes the pending state.

Stop (): Stops the process.

The above methods are prone to deadlock and are not recommended for use.

What do I do if I want to stop a thread now?

Lets the thread stop running by setting the flag bit. To stop, set a method so that the flag bit is false. As follows:

  

classMyThreadImplementsrunnable{Private Boolean flag = true; Defining Flag bits     Public voidrun () {inti = 0 ;  while( This. Flag) {System.out.println (Thread.CurrentThread (). GetName ()+ "Run, I =" + (i++)) ; }    }    Public  void Stop () {  this.flag = false; Modify Flag bit     }}; Public classstopdemo{ Public Static voidMain (String args[]) {MyThread my=NewMyThread (); Thread T=NewThread (My, "thread");//To create a thread objectT.start ();//Start Thread        Try{Thread.Sleep (30) ; }Catch(Exception e) {} my.stop (); //Modify flag bit, stop running    }};

Thread's life cycle, thread end

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.