这个程序验证了后台线程与用户线程的区别以及之间的关系,证明了只要所有的用户线程结束了,那么后台线程将必须结束!
import java.util.concurrent.TimeUnit; public class Test { public static void main(String[] args){ //将主线程的优先级设为低,优先执行main线程创建的线程 Thread.currentThread().setPriority(Thread.MIN_PRIORITY); Thread myThread=new Thread(new Runnable(){ public void run(){ while(true) { System.out.println("i will wait for you in shangling"); try { TimeUnit.MILLISECONDS.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }); myThread.setDaemon(true); //设置后台线程一定要写在start()方法的前面,要不然是无效的 myThread.setPriority(Thread.MAX_PRIORITY); myThread.start(); Thread userThread = new Thread(new Runnable(){ public void run(){ for(int i=0;i<5;i++) System.out.println("this is a user Thread"); } }); userThread.setPriority(Thread.MAX_PRIORITY); userThread.start(); System.out.println("the main thread is end" ); } }
在上面的程序中能体会到,当用户线程都结束时,虽然后台线程(幽灵线程)是一个死循环,但是只要所有的用户线程都结束了,那么系统会自动停止。要让后台线程执行得久一点,只有一个方法,那是延长用户线程的运行时间,例如在main()方法中添加sleep()方法进行延时。
这里要注意一点,不要利用sleep方法来精确计时,由于这种方法是依赖操作系统的,所以它的计时准确性是非常不可靠的,当休眠时间过长时可能会产生意想不到的事情发生!