本帖最后由 huoxy 于 2014-11-25 18:53 编辑
package cn.itheima.day12;
class StopThread2 implements Runnable
{
private boolean flag = true;
public synchronized void run()
{
while(flag)
{
try
{
//1.进入冻结状态,就不会读取到标记,从而线程无法结束
wait();
} catch (InterruptedException e)
{
System.out.println(Thread.currentThread().getName()+"...Exception");
//3.操作循环标记是线程结束
flag = false;
}
System.out.println(Thread.currentThread().getName()+"...running");
}
}
public void changeFlag()
{
flag = false;
}
}
public class StopThreadDemo2
{
public static void main(String[] args)
{
StopThread2 st = new StopThread2();
Thread t1 = new Thread(st);
Thread t2 = new Thread(st);
t1.start();
t2.start();
int num = 1;
while(true)
{
if(num==51)
{
//st.changeFlag();
//2.当没有指定的方式让冻结的线程恢复到运行状态时,
// 这时需要对冻结状态进行清除,强制让线程恢复到
// 运行状态中,这样就可以操作循环标记让线程结束
t1.interrupt();
t2.interrupt();
break;
}
System.out.println(Thread.currentThread().getName()+"....."+(num++));
}
System.out.println("Over!");
}
}
|
|