什麼是後臺線程(守護線程)
爲其他線程提供服務的線程,當所有其他線程結束的時候,後臺線程也就結束了,只要有一個線程沒有結束,那麼後臺線程就一直執行下去。
但是我們一般做多線程都是使用線程池,比如:
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
MyThread m1 = new MyThread();
m1.setDaemon(true);
service.execute(m1);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public class MyThread extends Thread {
@Override
public void run() {
super.run();
while(true)
System.out.println(111);
}
}
但是結果,確實守護線程並沒有起到任何作用,m1這個線程會一直運行下去。
但是在Thinking in java種,作者給出了方案:
public class DaemonThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setDaemon(true);
return t;
}
}
public class DaemonFromFactory implements Runnable {
@Override
public void run() {
while(true){
try {
Thread.sleep(100);
System.out.println(Thread.currentThread() + " " + this);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool(new DaemonThreadFactory());
IntStream.range(0,10).forEach(i->service.execute( new DaemonFromFactory()));
System.out.println("所有後臺進程開啓");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("end");
}
}
通過傳入一個ThreadFactory來對傳入的Runnable進行加工。