版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yerenyuan_pku/article/details/82832993
停止线程
如何停止线程呢?须知stop()已经过时,那就只有一种方案了,即run()结束。其原理是线程任务通常都有循环,因为开启线程就是为了执行需要一些时间的代码。只要控制住循环,就可以结束run方法,就可以停止线程了。那如何控制循环呢?很简单啦,只须弄个标记(定义变量)即可。
class StopThread implements Runnable
{
private boolean flag = true;
public void run()
{
while (flag)
{
System.out.println(Thread.currentThread().getName() + "....run");
}
}
public void changeFlag()
{
flag = false;
}
}
class MyStopThreadDemo
{
public static void main(String[] args)
{
StopThread st = new StopThread();
Thread t1 = new Thread(st);
Thread t2 = new Thread(st);
t1.start();
t2.start();
for (int x = 1; x <= 50; x++)
{
if (x == 40)
{
st.changeFlag();
}
System.out.println("main...." + x);
}
System.out.println("over");
}
}
此时,会有一种特殊情况——当线程处于了冻结状态时,就不会读取到标记了,那么线程显然就不会结束。即:
class StopThread implements Runnable
{
private boolean flag = true;
public synchronized void run()
{
while (flag)
{
try
{
wait();//t0、t1
}
catch (InterruptedException e)
{
System.out.println(Thread.currentThread().getName() + "............" + e.toString());
}
System.out.println(Thread.currentThread().getName() + "....run");
}
}
public void changeFlag()
{
flag = false;
}
}
class MyStopThreadDemo
{
public static void main(String[] args)
{
StopThread st = new StopThread();
Thread t1 = new Thread(st);
Thread t2 = new Thread(st);
t1.start();
t2.start();
for (int x = 1; x <= 50; x++)
{
if (x == 40)
{
st.changeFlag();
}
System.out.println("main...." + x);
}
System.out.println("over");
}
}
当没有指定的方式让冻结的线程恢复到运行状态时,这时需要对冻结进行清除,强制让线程恢复到运行状态中来,这样就可以操作标记让线程结束。Thread类中提供了该方法——interrupt()。如此,可将以上程序修改为:
class StopThread implements Runnable
{
private boolean flag = true;
public synchronized void run()
{
while (flag)
{
try
{
wait();//t0、t1
}
catch (InterruptedException e)
{
System.out.println(Thread.currentThread().getName() + "............" + e.toString());
flag = false;//自杀,return;是他杀
}
System.out.println(Thread.currentThread().getName() + "....run");
}
}
public void changeFlag()
{
flag = false;
}
}
class MyStopThreadDemo
{
public static void main(String[] args)
{
StopThread st = new StopThread();
Thread t1 = new Thread(st);
Thread t2 = new Thread(st);
t1.start();
t2.start();
for (int x = 1; x <= 50; x++)
{
if (x == 40)
{
//st.changeFlag();
t1.interrupt();//将t1线程中断。
t2.interrupt();//将t2线程中断。
}
System.out.println("main...." + x);
}
System.out.println("over");
}
}
小结
InterruptedException(中断异常)什么时候会发生呢?凡是线程处于冻结状态,如果强制把它恢复回来,那么必须发生的异常。能让线程处于冻结状态的方法不多,第一个就是sleep(),第二个就是wait()。