----------- 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会自行终止。