了解 join() 方法示例

2022-09-03 13:59:45

Java thread join() 方法让我有点困惑。我有以下示例

class MyThread extends Thread {
    private String name;
    private int sleepTime;
    private Thread waitsFor;

    MyThread(String name, int stime, Thread wa) { … }

    public void run() {
        System.out.print("["+name+" ");

        try { Thread.sleep(sleepTime); }
        catch(InterruptedException ie) { }

        System.out.print(name+"? ");

        if (!(waitsFor == null))
        try { waitsFor.join(); }
        catch(InterruptedException ie) { }

        System.out.print(name+"] ");

public class JoinTest2 {
    public static void main (String [] args) {
        Thread t1 = new MyThread("1",1000,null);
        Thread t2 = new MyThread("2",4000,t1);
        Thread t3 = new MyThread("3",600,t2);
        Thread t4 = new MyThread("4",500,t3);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

线程以什么顺序终止?


答案 1

什么实际上让你感到困惑?你没有提到任何具体的东西。Thread.join()

鉴于此(如文档所述),然后 将等待 完成,这将等待 完成,这将等待完成。Thread.join()Waits for this thread to diet4t3t2t1

因此将首先完成,然后是 、 和 。t1t2t3t4


答案 2

它将按顺序 t1、t2、t3、t4 终止...join 会导致当前正在执行的线程等待,直到调用它的线程终止。