Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Java 的 join() 方法:讓一個線程等另一個線程

在某個線程中呼叫另一個線程的 join(),效果是把 CPU 讓給對方,等到指定時間到或對方執行完畢,自己才繼續往下走。

示例一:加不加 join 的差別

package test;

public class TestJoin1 {
    public static void main(String[] args) throws InterruptedException {
        TheOtherThread tot = new TheOtherThread();
        Thread t = new Thread(tot);
        t.start();
        // t.join();
        System.out.println("main");
    }
}

class TheOtherThread implements Runnable {
    @Override
    public void run() {
        try {
            for (int i = 0; i < 10; i++) {
                Thread.sleep(1000);
                System.out.println(i);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

不呼叫 join 時,輸出順序是:

main
0
1
2
3
4
5
6
7
8
9

把 t.join() 前面的註解拿掉之後,順序變成:

0
1
2
3
4
5
6
7
8
9
main

也就是 main 執行緒被擋住,必須等 t 跑完才能印出 "main"。

示例二:三個線程的等待關係

package test;

import java.util.Date;

public class TestJoin {
    public static void main(String[] args) {
        DateThreat dt1 = new DateThreat("a");
        DateThreat dt2 = new DateThreat("b");

        Thread t1 = new Thread(dt1);
        Thread t2 = new Thread(dt2);

        DateThreat dt3 = new DateThreat("c", t2);
        Thread t3 = new Thread(dt3);

        t1.start();
        t2.start();
        t3.start();
    }
}

class DateThreat implements Runnable {
    private String name;
    private Thread t;

    public DateThreat(String name) {
        this.name = name;
    }

    public DateThreat(String name, Thread t) {
        this.name = name;
        this.t = t;
    }

    @Override
    public void run() {
        try {
            System.out.println(this.name + " begin : " + new Date());
            if (t != null) {
                t.join();          // c 必須等 b 結束
            }
            for (int i = 0; i < 10; i++) {
                Thread.sleep(1000);
                System.out.println(this.name + " : " + i);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(this.name + " end : " + new Date());
    }
}

a、b、c 三個線程幾乎同時啟動,但 c 因為對 b 呼叫了 join(),永遠要等 b 執行完才真正開始跑。實際輸出的時間戳很能說明問題:b 與 a 幾乎同步推進,b 結束後 c 才從 0 印起,整體時間軸被拉長了 10 秒。

這也是 join 最典型的用途——建立線程之間的先後依賴,而不必靠 sleep 去「猜」對方跑完了沒。多跑幾次你會發現 a 與 b 的交錯順序會變,但 c 一定在 b 之後,這正是 join 提供的確定性。

Copyright © Linux教程網 All Rights Reserved