2016-11-10 65 views

回答

1

JVM垃圾收集線程是一個典型的守護線程,你可以創建守護線程就像正常的線程,並調用線程等和setDaemon(true)這裏我做一個簡單的演示:

/** 
* Created by crabime on 11/10/16. 
*/ 
public class DaemonTest extends Thread { 
    @Override 
    public void run() { 
     for (int i = 0; i < 1000; i++){ 
      System.out.println(getName() + " " + i); 
     } 
    } 

    public static void main(String[] args) { 
     DaemonTest d = new DaemonTest(); 
     d.setDaemon(true); 
     d.start(); 
     try { 
      Thread.sleep(200);//after 200 million seconds, main thread ends and no matter DaemonTest thread run to the end or not, it will stop 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
    } 

}