黑马程序员技术交流社区
标题:
关于停止线程
[打印本页]
作者:
Fightingforever
时间:
2014-10-24 23:01
标题:
关于停止线程
class StopThread implements Runnable
{
private boolean flag=true;
public synchronized void run()
{
while(flag)
try
{
this.wait();
}
catch(InterruptedException e)
{
System.out.println(Thread.currentThread().getName()+"...Exception");
}
System.out.println(Thread.currentThread().getName()+"...run");
}
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++==60)
{
st.changeFlag();
break;
}
System.out.println(Thread.currentThread().getName()+"......"+num);
}
}
}
有谁能帮忙分析一下这段代码
复制代码
作者:
zd12345
时间:
2014-10-25 13:51
class StopThread implements Runnable
{
private boolean flag=true; //定义线程结束标记
public synchronized void run() //将整个run方法定义为同步方法
{
while(flag) //如果标记为真,继续循环。否则结束线程。
try
{
this.wait(); //线程启动后,执行wait方法,进入冻结状态。
}
catch(InterruptedException e)
{
System.out.println(Thread.currentThread().getName()+"...Exception");
}
System.out.println(Thread.currentThread().getName()+"...run");
}
public void changeFlag() //对外提供的结束线程方法:将线程结束标记置为false
{
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++==60) //如果循环次数达到60,便执行线程的结束方法,将flag标记为false。并跳出循环。
{
st.changeFlag();
break;
}
System.out.println(Thread.currentThread().getName()+"......"+num);
}
}
}
复制代码
在主线程中执行线程的changeFlag方法并不能结束两个线程。因为两个线程启动后便进入冻结状态,不能检测到线程结束标记flag。此种情况应在主线程中先执行changeFlag方法,再执行两个线程的interrupt方法,使线程解除冻结状态,继续循环,然后检测到线程结束标记并结束。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2