如果你想让你的线程在后台运行,那么你可以调用:
Thread.setDaemon(true);
但是有一点需要注意的:
如果你设置你的线程后守护线程,那么如果主线程执行完了,那么后台程序也会跟着退出!
样例代码如下:
class DaemonThread implements Runnable
{
public synchronized void run()
{
while(true)
{
System.out.println(Thread.currentThread().getName()+"....run");
}
}
}
public class DaemonThreadDemo
{
public static void main(String[] args) throws Exception
{
DaemonThread st = new DaemonThread();
Thread t1 = new Thread(st);
Thread t2 = new Thread(st);
/**
* 如果面两句注释掉,那么程序会一直运行
* 如果没有注释,那么运行一会儿程序就会退出
*/
t1.setDaemon(true);
t2.setDaemon(true);
t1.start();
t2.start();
Thread.sleep(10);
System.out.println("over");
}
}