1、后台线程是给非后台线程做辅助的,提供服务的,并且不是不可或缺的,但是当非后台线程全部结束是,后台线程就会被终止了。
2、创建后台线程:只要调用线程的setDaemon(True)方法就可以将其设置为后台线程了。
3、
public class BasicThread implements Runnable{
public void run(){
try{
while(true){
TimeUnit.MILLISECONDS.sleep(2000);
System.out.println(Thread.currentThread()+" "+this);
}
}catch (InterruptedException e){
}
}
public static void main(String[]args){
Thread thread=new Thread(new BasicThread());
thread.setDaemon(true);
thread.start();
try {
System.out.println("all daemon started");
Thread.sleep(5000);
}catch (InterruptedException e){
}
}
}
结果:
all daemon started
Thread[Thread-0,5,main] BasicThread@5323cf50
Thread[Thread-0,5,main] BasicThread@5323cf50
说明:thread线程在死循环中,并且每隔2秒这个线程都会输出
Thread[Thread-0,5,main] BasicThread@5323cf50
但是由于主线程sleep了5秒钟,所以5秒之后主线程苏醒,并运行结束,这时,后台线程也就结束了,不再输出。