黑马程序员---守护线程的用法

----------- android培训、java培训、java学习型技术博客、期待与您交流! ------------


java线程分为用户线程(前台线程)和后台线程(守护线程),当前台线程全部挂起,或者interrupt掉后,后台线程会自动终止

一般线程终止,是让线程的run()方法完成,来实现线程的终止,代码如下:





public 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 StopThreadDemo
{
public static void main(String[] args)
{
StopThread st=new StopThread();

Thread t1=new Thread(st);
Thread t2=new Thread(st);
t1.setDaemon(true);
t2.setDaemon(true);
t1.start();
t2.start();
int num=0;
while(true)
{
if(num++==60)
{
st.changeFlag();
break;
}

System.out.println(Thread.currentThread().getName()+"...."+num);
}
System.out.println("over");
}
}


但是上述代码如果稍加改变改为:






public class  StopThread  implements Runnable
{
private boolean flag=true;
public synchronized void run()
{
while(flag)
{
try
{
wait();
}
catch(InterruptedException e){ System.out.println(e.toString());}
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.setDaemon(true);
//t2.setDaemon(true);
t1.start();
t2.start();
int num=0;
while(true)
{
if(num++==60)
{
st.changeFlag();
break;
}

System.out.println(Thread.currentThread().getName()+"...."+num);
}
System.out.println("over");
}
}

将run()方法加锁,那么在run方法中try{}中wait()了,这样程序运行时候,t1和t2线程都会被挂起,那么执行st.changFlag()方法后,虽然flag变化了,但是t1和t2处于挂起状态,就不会再判断flag,t1和t2线程就不会中断

解决这个问题的办法就是在

t1.start();和t2.start()语句前面加上t1.setDaemon(true);t2.setDaemon(true);将t1和t2.设置成守护线程,那么前台main线程运行完后,守护线程t1和t2会自行终止。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值