了解join()

and*_*and 4 java multithreading join scjp

假设一个线程A正在运行.我有另一个线索B,谁不是.B已经启动,处于可运行状态.

如果我打电话B.join()会怎么样?

是暂停执行A还是等待A的run()方法完成?

bra*_*ter 9

join()将使当前正在执行的线程等待它被调用的线程死掉.

所以 - 如果A正在运行,并且你调用B.join(),A将停止执行,直到B结束/死亡.


Eug*_*ota 7

加入等待直到线程死亡.如果你在一个死线程上调用它,它应该立即返回.这是一个演示:

public class Foo extends Thread {

    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println("Start");

        Foo foo = new Foo();
        try {
            // uncomment the following line to start the foo thread.
            // foo.start();
            foo.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Finish");
    }

    public void run() {
        System.out.println("Foo.run()");
    }

}
Run Code Online (Sandbox Code Playgroud)