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