標籤:ima nts 方法 print ext i++ trace dex 守護線程
- package daemonThread;
- /*setDaemon(true)方法將線程設定為守護線程,線程的Daemon預設值為false
- * 只要當前JVM執行個體中存在任何一個非守護線程沒有結束,守護線程就在工作
- * 當進程中不存在非守護線程,則守護線程隨著JVM一同結束
- * GC(記憶體回收行程)就是一個守護線程
- * 本例中main線程雖然先結束,但是testThread線程還在工作,所以只有當testThread線程也結束,才停止列印i */
- class MyThread extends Thread{
- private int i = 0;
- @Override
- public void run(){
- super.run();
- try{
- while(true){
- i++;
- System.out.println("i="+i);
- Thread.sleep(1000);
- }
- }catch(InterruptedException ie){
- ie.printStackTrace();
- }
- }
- }
- class testThread extends Thread{
- @Override
- public void run(){
- try{
- Thread.sleep(10000); //testThread線程約10秒後結束
- System.out.println(Thread.currentThread().getName()+"線程結束!");
- }catch(InterruptedException ie){
- ie.printStackTrace();
- }
- }
- }
- public class Run {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- try{
- MyThread thread = new MyThread();
- thread.setName("thread");
- thread.setDaemon(true); //將thread線程設為守護線程
- thread.start();
- testThread t = new testThread();
- t.setName("testThread");
- t.start();
- Thread.sleep(5000); //main線程在這裡停留5秒
- System.out.println("主線程結束了");//5秒後main線程結束了,但是testThread線程還在執行,所以守護線程繼續工作
-
- /*當所有線程都結束時,thread線程也隨之結束*/
- }catch(InterruptedException ie){
- ie.printStackTrace();
- }
- }
- }
運行結果如
java守護線程的理解