Java如何使用join方法等待线程完成?

如果希望一个线程一直工作到另一个线程死亡,可以使用join()方法将该线程连接到另一个线程的末尾。例如,您希望线程B只在线程A完成其工作之前工作,然后您希望线程B加入线程A。

package org.nhooo.example.lang;

public class ThreadJoin implements Runnable {
    private int numberOfLoop;

    private ThreadJoin(int numberOfLoop) {
        this.numberOfLoop = numberOfLoop;
    }

    public void run() {
        System.out.println("[" +
            Thread.currentThread().getName() + "] - Running.");

        for (int i = 0; i < this.numberOfLoop; i++) {
            System.out.println("[" +
                Thread.currentThread().getName() + "] " + i);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("[" +
            Thread.currentThread().getName() + "] - Done.");
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(new ThreadJoin(10), "FirstThread");
        Thread t2 = new Thread(new ThreadJoin(20), "SecondThread");

        try {
            // 启动t1并等待该线程死亡
            // 启动t2线程。
            t1.start();
            t1.join();

            // 从t2开始
            t2.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}