所谓的后台线程,是指在程序运行的时候在后台提供一种通用服务的线程,并且这种线程并不属于程序中不可或缺的部分。因此,当所有的非后台线程结束的时候,程序也就终止,同时会杀死所有的后台线程。
实例 2 :
package com.thread;
import java.util.concurrent.TimeUnit;
public class SimpleDaemons implements Runnable{
public void run() {
while(true) {
try {
TimeUnit.MILLISECONDS.sleep(100);
System.out.println(Thread.currentThread() + " " + this);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 10; i++) {
Thread daemo = new Thread(new SimpleDaemons());
daemo.setDaemon(true);
daemo.start();
}
System.out.println("All daemons started");
//如果去掉sleep,run方法中的语句不会输出。说明main也是非后台线程
TimeUnit.MILLISECONDS.sleep(180);
}
}
实例 2 :
package com.thread;
import java.io.IOException;
public class ResponsveUI extends Thread {
private static volatile double d = 1;
public ResponsveUI() {
setDaemon(true);
start();
}
public void run() {
while(true) {
d = d + (Math.PI + Math.E);
}
}
public static void main(String[] args) throws Exception {
// new UnresponsiveUI(); //must kill this process
new ResponsveUI();
System.in.read();
System.out.println(d);
}
}
class UnresponsiveUI {
private volatile double d = 1;
public UnresponsiveUI() throws Exception{
while (d > 0) {
d = d + (Math.PI + Math.E);
}
System.in.read();
}
}