(一)線程管理_5---等待線程終止

等待線程終止

在有的時候,須要等待一個線程執行完後才能繼續執行後面的程序;好比資源的加載,只有當加載完全部的資源後,在繼續執行業務邏輯部分;那麼Thread類的join方法,Thread.join()就起這個做用; 當一個線程使用一個線程對象調用了join()方法,那麼這個線程對象將會被掛起,直到這個線程對象執行完畢後,調用線程纔會繼續執行;java

動手實現

public class ResourceLoader implements Runnable {
    //模擬資源加載
    @Override
    public void run() {
        System.out.printf("Beginning data sources loadding:%s\n", new Date());
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.printf("Data source loading has finished:%s\n", new Date());
    }

    public static void main(String[] args) {
        Thread thread1 = new Thread(new ResourceLoader(), "localResourceLoader");
        Thread thread2 = new Thread(new ResourceLoader(), "remoteResourceLoader");
        thread1.start();
        thread2.start();
        //主線程等待資源加載完畢
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.printf("Main:Resource has been loaded:%s\n", new Date());

    }
}

一次運行結果:

Beginning data sources loadding:Fri Oct 31 00:09:37 CST 2014
Beginning data sources loadding:Fri Oct 31 00:09:37 CST 2014
Data source loading has finished:Fri Oct 31 00:09:41 CST 2014
Data source loading has finished:Fri Oct 31 00:09:41 CST 2014
Main:Resource has been loaded:Fri Oct 31 00:09:41 CST 2014
ide

要點

Java提供了兩個方法線程

  1. join(long milliseconds)
  2. join(long milliseconds,long nanos)

第二個方法接受兩個參數,毫秒,納秒code

join方法是Thread類非靜態方法對象

相關文章
相關標籤/搜索