- import static java.util.concurrent.TimeUnit.*;
- public class DaemonTest {
- public static void main(String[] args) throws InterruptedException {
- Runnable r = new Runnable() {
- public void run() {
- for (int time = 10; time > 0; --time) {
- System.out.println("Time #" + time);
- try {
- SECONDS.sleep(2);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- };
- Thread t = new Thread(r);
- t.setDaemon(true); // try to set this to "false" and see what happens
- t.start();
- System.out.println("Main thread waiting...");
- SECONDS.sleep(6);
- System.out.println("Main thread exited.");
- }
- }
當t.setDaemon(true),即t為Daemon線程時,執行結果如下:
t為Daemon線程的輸出:
Time #10
Time #9
Time #8
Main thread exited.
Time #7
當t.setDaemon(false),即t為非守護線程時,執行結果如下:
Main thread waiting...
Time #10
Time #9
Time #8
Main thread exited.
Time #7
Time #6
Time #5
Time #4
Time #3
Time #2
Time #1
總結: 1、當主線程一結束、(非守護線程的)子線程不會立即結束。 2、當主線程一結束,(守護線程的)子線程會立即結束。 3、子線程對象,在調用start()方法之前,通過調用setDaemon(true),将本子線程設定為守護線程。