The so-called daemon thread refers to the thread that provides a general service in the background when the program is running, and this thread is not an indispensable part of the program . Therefore, when all the non-background threads end, the program is terminated, and all non-background threads in the process are killed. For example, the execution of main() is a non-background thread.
The thread can be set as a background thread before the thread is started by the setDaemon() method.
You can customize the attributes (background, priority, name) of the thread created by the Excecutor by writing a customized ThreadFactory.
class DaemonThreadFactory implements ThreadFactory{
@Override
public Thread newThread(Runnable r) {
// TODO Auto-generated method stub
Thread t=new Thread(r);
t.setDaemon(true);
return t;
}
}
public class DaemonFromFactory implements Runnable{
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
ExecutorService exec=Executors.newCachedThreadPool(new DaemonThreadFactory());
for(int i=0;i<10;i++) {
exec.execute(new DaemonFromFactory());
}
System.out.println("All daemons started");
TimeUnit.MILLISECONDS.sleep(500);
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true) {
try{
TimeUnit.MILLISECONDS.sleep(100);
System.out.println(Thread.currentThread()+" "+this);
}catch(InterruptedException e) {
System.out.println("Interrupted");
}
}
}
}
Among them, the non-background thread executing main() sleeps, so that the effect of the background thread startup can be seen on the window. If the non-background thread executing main() is not allowed to sleep, then only the effect of the creation of the background thread will be seen . Modulate the sleep time of the non-background thread that executes main() for a longer time, and you will see a longer background thread running track. If the sleep time is adjusted to a small enough time, the background thread will not be seen. The execution track.
You can determine whether a thread is a background thread by calling the isDaemon () method.
If it is a background thread, all threads it creates will be automatically set as background threads.