Java 线程 Join 示例

Java Thread join方法可用於暫停當前執行緒的執行,直到指定的執行緒死亡。有三個重載的join函數。

Java Thread join

public final void join(): 這個java執行緒的join方法將當前執行緒放在等待狀態,直到調用該方法的執行緒死亡。如果執行緒被中斷,則會拋出InterruptedException異常。public final synchronized void join(long millis): 這個java執行緒的join方法用於等待調用它的執行緒死亡,或者等待指定的毫秒數。由於執行緒的執行取決於操作系統的實現,它不能保證當前執行緒僅等待指定的時間。public final synchronized void join(long millis, int nanos): 這個java執行緒的join方法用於等待執行緒死亡,等待時間為給定的毫秒數加上納秒數。以下是一個簡單的示例,顯示了Thread join方法的使用。該程序的目標是確保主執行緒是最後一個完成的,並且第三個執行緒只有在第一個執行緒死亡後才啟動。

package com.journaldev.threads;

public class ThreadJoinExample {

    public static void main(String[] args) {
        Thread t1 = new Thread(new MyRunnable(), "t1");
        Thread t2 = new Thread(new MyRunnable(), "t2");
        Thread t3 = new Thread(new MyRunnable(), "t3");
        
        t1.start();
        
        //在等待2秒後或當第二個線程結束時開始第二個線程
        try {
            t1.join(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        t2.start();
        
        //當第一個線程結束後才開始第三個線程
        try {
            t1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        t3.start();
        
        //在主線程結束前讓所有線程完成執行
        try {
            t1.join();
            t2.join();
            t3.join();
        } catch (InterruptedException e) {
            // TODO 自動生成的捕獲區塊
            e.printStackTrace();
        }
        
        System.out.println("All threads are dead, exiting main thread");
    }

}

class MyRunnable implements Runnable{

    @Override
    public void run() {
        System.out.println("Thread started:::"+Thread.currentThread().getName());
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Thread ended:::"+Thread.currentThread().getName());
    }
    
}

上述程序的輸出是:

Thread started:::t1
Thread started:::t2
Thread ended:::t1
Thread started:::t3
Thread ended:::t2
Thread ended:::t3
All threads are dead, exiting main thread

這就是關於Java線程join示例的快速總結。

Source:
https://www.digitalocean.com/community/tutorials/java-thread-join-example