线程加入

让子线程加入父线程, 父线程会等待子线程执行完毕后再继续执行

不使用join的情况

class Parent {
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            if (i == 5) {
                Thread child = new Child();
                child.start();
            }
            System.out.println("parent: " + i);
        }
    }
}
class Child extends Thread {
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("child: " + i);
        }
    }
}

结果 (每次结果不一样):

parent: 0
parent: 1
parent: 2
parent: 3
parent: 4
parent: 5
child: 0
child: 1
parent: 6
parent: 7
parent: 8
child: 2
child: 3
child: 4
parent: 9
child: 5
child: 6
child: 7
child: 8
child: 9

使用join的情况

class Parent {
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            if (i == 5) {
                Thread child = new Child();
                child.start();
                child.join();
            }
            System.out.println("parent: " + i);
        }
    }
}
class Child extends Thread {
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("child: " + i);
        }
    }
}

结果 (确定的):

parent: 0
parent: 1
parent: 2
parent: 3
parent: 4
child: 0
child: 1
child: 2
child: 3
child: 4
child: 5
child: 6
child: 7
child: 8
child: 9
parent: 5
parent: 6
parent: 7
parent: 8
parent: 9

join(millis) 接收一个参数, 可以指定父线程等待多少毫秒后继续执行, 若不指定, 则等待子线程完全执行完毕后继续执行

MIT Licensed | Copyright © 2018-present 滇ICP备16006294号

Design by Quanzaiyu | Power by VuePress