天天看點

線程間通信Thread.join

在很多應用場景中存在這樣一種情況,主線程建立并啟動子線程後,如果子線程要進行很耗時的計算,那麼主線程将比子線程先結束,但是主線程需要子線程的計算的結果來進行自己下一步的計算,這時主線程就需要等待子線程,java中提供可join()方法解決這個問題。

join()方法的作用,是等待這個線程結束;

也就是說,t.join()方法阻塞調用此方法的線程(calling thread)進入 TIMED_WAITING 狀态,直到線程t完成,此線程再繼續;

通常用于在main()主線程内,等待其它線程完成再結束main()主線程

package com.dongguo.sync;


/**
 * @author Dongguo
 * @date 2021/8/23 0023-23:01
 * @description: join
 */
public class ThreadDemo4 {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName() + "開始執行");
        Thread threadA = new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "開始執行");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "執行結束");
        }, "ThreadA");


        Thread threadB = new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "開始執行");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "執行結束");
        }, "ThreadB");

        try {
            threadA.start();
            threadA.join();
            threadB.start();
            threadB.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "執行結束");
    }
}
運作結果:
main開始執行
ThreadA開始執行
ThreadA執行結束
ThreadB開始執行
ThreadB執行結束
main執行結束
           

每個線程的終止的前提是前驅線程的終止,每個線程等待前驅線程終止後,才從join方法傳回,實際上,這裡涉及了等待/通知機制,即下一個線程的執行需要接受前驅線程結束的通知。