Methods for external threads to stop Java child threads

Source: Internet
Author: User

First, Thread.stop ()
Officially not recommended, Because it is inherently unsafe.


Two, mode one
1. Threading Class Example

 Public classThreadT1 implements Runnable {PrivateThread Threadthis;  Public voidstart () {Threadthis=NewThread ( This);    Threadthis.start (); }     Public voidStop () {threadthis=NULL; }     Public voidrun () {Thread thisthread=Thread.CurrentThread ();  while(Threadthis = =thisthread) {System. out. println ("lalala~"); //Do YOUR work!} System. out. println ("stopped!!!"); }}            


2. Using the example

New// Create thread and start / Stop this thread  


Three, mode two
1. Threading Class Example

 Public classThreadT2 extends Thread {PrivateBoolean stop =false;  Public voidStopbymark () {Stop=true; }     Public voidrun () { while(!stop) {System. out. println ("lalala~"); //Do YOUR work!} System. out. println ("stopped!!!"); }}


2. Using the example

New// Create thread and start / Stop this thread  


Attached, about Thread.Interrupt ()
The thread can also be stopped in this way.
Prerequisites:

 Public void run () {    try  {        thread.sleep ();     Catch // The method that captures the interruptedexception must exist, and the    stop method is called when the throw occurs.      e.printstacktrace ();    Stopbymark ();    }}

Methods for external threads to stop Java child threads

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.