java中的守护线程设置:setDaemon(true);
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package thread; 2 3 /** 4 * 兔子的线程 5 * @author superdrew 6 */ 7 public class RabbitRunnable implements Runnable{ 8 9 public void run() { 10 while(true){ 11 System.out.println("兔子领先了....加油!!!!"+ 12 Thread.currentThread().getName()+" "+Thread.currentThread().getPriority()); 13 } 14 } 15 16 }
乌龟线程:TortoiseThread.java
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package thread; 2 3 public class TortoiseThread extends Thread{ 4 5 private String name; 6 7 public TortoiseThread(){} 8 9 public TortoiseThread(String name){ 10 super(name); 11 } 12 13 public void run() { 14 while(true){ 15 System.out.println("乌龟领先了。。。加油。。。。。。"+getName() +" "+getPriority()); 16 } 17 } 18 }
测试线程--主线程
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package thread; 2 /** 3 * 功能:龟兔赛跑 4 * 使用线程 5 * setDaemon----守护线程 6 * 可以将指定的线程设置成后台线程 7 创建后台线程的线程结束时,后台线程也随之消亡 8 总结:1.作用,让当前线程成为后台线程(守护线程,寄生线程) 9 2.位置:位于start前面(join是位于start后面) 10 3.开发中实际的运用: jvm的垃圾回收器 11 12 * @author superdrew 13 * 14 */ 15 public class TestThread1 { 16 public static void main(String[] args) { 17 RabbitRunnable rr = new RabbitRunnable(); 18 Thread tr = new Thread(rr); 19 tr.setName("兔子线程"); 20 tr.setDaemon(true);//设置守护线程 21 tr.start(); 22 23 int i =1; 24 while(i<100){ 25 System.out.println("乌龟领先了。。。加油。。。。。。"+Thread.currentThread().getName()); 26 i++; 27 } 28 } 29 }