2016-01-13 84 views
0
public class TestThread { 

    public static void main(String[] args) { 

     System.out.println("Main Prgm Started..."); 
     Thread t1=new Thread(new Runnable() { 

      @Override 
      public void run() { 

       System.out.println("Thread is running.."); 
      } 
     }); 

     t1.start(); 

     System.out.println("Main Prgm Exited..."); 
    } 
} 

輸出是:爲什麼線程在執行main方法後運行?

Main Prgm Started... 
Main Prgm Exited... 
Thread is running.. 
+0

因爲它運行在一個單獨的線程?除非你同步你的線程,否則它們獨立運行,沒有特定的順序。 – Thilo

回答

2

Java程序將繼續任何非daemon線程運行時運行。從下面的鏈接可以看出:「守護進程線程是一個線程,當程序完成但線程仍在運行時,它不會阻止JVM退出。守護進程線程的一個例子就是垃圾回收,您可以使用setDaemon()方法來更改線程守護程序屬性。「 What is Daemon thread in Java?

默認情況下,所有創建的線程都是守護進程。您需要將其設置爲非守護進程。

1

你不會要求主線程在退出之前等待t1完成,因此兩個線程之間根本沒有同步(並且你沒有任何關於何時它們每個都會執行它們的println的任何保證) 。

如果你想主線程等待其他那麼你應該使用join()功能,如:

t1.start(); 
t1.join(); 
System.out.println("Main Prgm Exited..."); 
0

或使用CountDownLatch:

import java.util.concurrent.CountDownLatch; 

公共類TestThread {

public static void main(String[] args) { 

    final CountDownLatch countDownLatch = new CountDownLatch(1); 

    System.out.println("Main Prgm Started..."); 
    Thread t1=new Thread(new Runnable() { 

     @Override 
     public void run() { 

      System.out.println("Thread is running.."); 
      countDownLatch.countDown(); 
     } 
    }); 

    t1.start(); 

    try { 
     countDownLatch.await(); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
    System.out.println("Main Prgm Exited..."); 
} 

}

0

如果您想知道程序何時完成,您需要關閉掛鉤。從主返回不會殺死程序。

public static void main(String[] args) { 

    System.out.println("Main Prgm Started..."); 
    Thread t1=new Thread(new Runnable() { 

     @Override 
     public void run() { 

      System.out.println("Thread is running.."); 
      try { 
       Thread.sleep(1000); 
      } catch (InterruptedException e) {} 
      System.out.println("Thread is done.."); 
     } 
    }); 
    t1.start(); 

    Runtime.getRuntime().addShutdownHook(new Thread() { 
     public void run() { 
      System.out.println("Main Prgm Exited..."); 
     } 
    }); 
} 
相關問題