Thread的join方法


Thread的join方法

關於join官方的解釋是 Waits for this thread to die. 也就是等待一個線程結束。

我們來先來一段代碼來引入join的使用場景(這里使用了java8的IntStream)

/**
 * @program: ThreadDemo
 * @description: 正常兩個線程交替執行
 * @author: hs96.cn@Gmail.com
 * @create: 2020-09-03
 */
public class ThreadJoin {
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            IntStream.range(1, 1_000).forEach(i ->
                    System.out.println(Thread.currentThread().getName() + "->" + i)
            );
        }, "t1");
        t1.start();

        IntStream.range(1, 1_000).forEach(i ->
                System.out.println(Thread.currentThread().getName() + "->" + i)
        );
    }
}

運行結果如下 :

可以看到正常兩個線程是交替執行的。如果我們想線程t1執行完再執行main線程呢,這里就需要使用join了:

/**
 * @program: ThreadDemo
 * @description: 使用join方法線程t1結束后才會執行線程main
 * @author: hs96.cn@Gmail.com
 * @create: 2020-09-03
 */
public class ThreadJoin {
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            //java8 IntStream
            IntStream.range(1, 1_000).forEach(i ->
                    System.out.println(Thread.currentThread().getName() + "->" + i)
            );
        }, "t1");
        t1.start();
        t1.join();

        IntStream.range(1, 1_000).forEach(i ->
                System.out.println(Thread.currentThread().getName() + "->" + i)
        );
    }
}

運行結果如下:

再增加一個子線程,join一下試試:

/**
 * @program: ThreadDemo
 * @description: 使用join方法線程t1結束后才會執行線程main
 * @author: hs96.cn@Gmail.com
 * @create: 2020-09-03
 */
public class ThreadJoin {
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            //java8 IntStream
            IntStream.range(1, 1_000).forEach(i ->
                    System.out.println(Thread.currentThread().getName() + "->" + i)
            );
        }, "t1");
        Thread t2 = new Thread(() -> {
            IntStream.range(1, 1_000).forEach(i ->
                    System.out.println(Thread.currentThread().getName() + "->" + i)
            );
        }, "t2");

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        IntStream.range(1, 1_000).forEach(i ->
                System.out.println(Thread.currentThread().getName() + "->" + i)
        );
    }
}

結果和我們的預期一樣,兩個子線程執行完之后才執行main線程。

join方法還支持幾個參數:

一個毫秒級別,一個微妙級別,就是最多等待這個線程執行多久。

代碼來測試一下:

/**
 * @program: ThreadDemo
 * @description: join(long millis), join(long millis, int nanos)
 * @author: hs96.cn@Gmail.com
 * @create: 2020-09-03
 */
public class ThreadJoin2 {
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            try {
                System.out.println("t1 is running...");
                Thread.sleep(5_000);
                System.out.println("t1 is done.");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t1.start();
        //只等待t1線程3秒
        t1.join(3_000);
        System.out.println("main thread is running...");
    }
}

運行效果如下:

流程如下:程序開始進入t1線程,開始執行t1線程run方法,t1線程run方法打印t1 is running...,然后開始sleep5秒,這時候程序執行到t1.join(3_000);也就是只等待t1線程3秒,等待結束后main線程打印main thread is running...,再過大約2秒,t1sleep結束,打印t1 is done。后面的我們就不測試了,現在引出一個新的問題:

一些嵌入式的HTTP Server,比如jetty,為什么把任務啟動,一會之后會自動掛掉?其實原因很簡單就是在主線程退出之后會把http server掛掉(守護線程),避免占用端口、浪費資源。解決辦法是使用Thread.currentThread().join();。讓當前線程執行,直到當前線程死掉。

測試代碼如下:

/**
 * @program: ThreadDemo
 * @description: join(long millis), join(long millis, int nanos)
 * @author: hs96.cn@Gmail.com
 * @create: 2020-09-03
 */
public class ThreadJoin2 {
    public static void main(String[] args) throws InterruptedException {
       Thread.currentThread().join();
    }
}

運行效果如下:

可以看到currentThread一直在等待,thread done....永遠不會輸出出來。

接下來結合一個案例感受一下join在多線程中的使用場景:比如我們啟動多個線程來采集服務器節點的信息,那么我們該如何保證唯一的采集結束時間呢?

/**
 * @program: ThreadDemo
 * @description: 采集服務器節點的信息的例子。問題:多個線程如何得到唯一的采集結束時間?
 * @author: hs96.cn@Gmail.com
 * @create: 2020-09-03
 */
public class ThreadJoin3 {
    public static void main(String[] args) throws InterruptedException {
        long startTimestamp = System.currentTimeMillis();

        // 假設有三台機器,開啟三個線程。
        Thread m1 = new Thread(new CaptureRunnable("M1", 1_000L));
        Thread m2 = new Thread(new CaptureRunnable("M2", 2_000L));
        Thread m3 = new Thread(new CaptureRunnable("M3", 3_000L));

        m1.start();
        m2.start();
        m3.start();

        long endTimestamp = System.currentTimeMillis();

        System.out.printf("Save data begin timestamp is %s, end timestamp is %s\n", startTimestamp, endTimestamp);
        System.out.printf("Spend time is %s", endTimestamp - startTimestamp);
    }
}

/**
 * 采集服務器節點的任務。
 */
class CaptureRunnable implements Runnable {
    // 機器節點的名稱
    private String machineName;
    // 采集花費時間
    private long spendTime;

    public CaptureRunnable(String machineName, long spendTime) {
        this.machineName = machineName;
        this.spendTime = spendTime;
    }

    @Override
    public void run() {
        // do the really capture data.
        try {
            Thread.sleep(spendTime);
            System.out.printf(machineName + " completed data capture at timestamp [%s] and successful.\n", System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public String getResult() {
        return machineName + " finish.";
    }
}

運行效果如下:

可以看到三個線程還沒走完,就提前把時間打印出來了,這個不是我我們想要的效果,那么我們讓三個線程join一下試試:

// 假設有三台機器,開啟三個線程。
Thread m1 = new Thread(new CaptureRunnable("M1", 1_000L));
Thread m2 = new Thread(new CaptureRunnable("M2", 2_000L));
Thread m3 = new Thread(new CaptureRunnable("M3", 3_000L));

m1.start();
m2.start();
m3.start();
m1.join();
m2.join();
m3.join();

運行效果如下:

這樣就達到我們想要的效果了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM