Ways to stop Java threads

Source: Internet
Author: User

Ways to stop Threads:

Remember a little, the thread stops,

1. I ran out of it,

2. If an infinite loop is outside, it can only be manipulated with the flag flag.

But when the thread is in a frozen state (blocking), Sleep,wait,join, (these three methods throw an exception.) )

The flag is not read.

At this point, we want to clear the frozen state of the thread and let it go back to running.


If the thread does not have a statement that makes it freeze, inierrupt () does nothing.

The interrupt () method causes the Sleep,wait,jion method to throw an exception.

Then, we operate in the statement that handles the exception.


I recommend the way: do not change the tag in the catch,

Or call the method of changing the tag, then, follow the interrupt.

St.changeflag ();

T1.interrupt ();

In this way, the thread is stopped regardless of whether there is a blocked method in the thread.



Class Stopthread implements Runnable

{

Private Boolean flag=true;


public void Run ()

{

while (flag)

{

Synchronized (This)

{

Try

{

Wait ();

}

catch (Exception e)

{

System.out.println (Thread.CurrentThread (). GetName () + "... Exception ");

Flag=false;

}

}

}


public void Changeflag ()

{

Flag=false;

}

}


Class Stopthreaddemo

{

public static void Main (string[] args)

{

Stopthread st=new Stopthread ();

Thread T1=new Thread (ST);

Thread T2=new Thread (ST);

T1.start ();

T2.start ();


int num=0;


while (true)

{

if (num++==10000)

{

St.changeflag ();

T1.interrupt ();

T2.interrupt ();

Break

}

System.out.println (Thread.CurrentThread (). GetName () + "..." +num);

}


}

}


This article is from the "thick Product Thin Hair" blog, please make sure to keep this source http://duanzhenyue.blog.51cto.com/9360091/1550144

Ways to stop Java 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.