java join()方法

当A线程执行到了B线程的join()方法时,A就会等待,等B线程都执行完,A才会执行。

join可以用来临时加入线程执行。

class Demo implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println(Thread.currentThread().getName()+"......"+i);
        }
    }
}
public class JoinDemo {
    public static void main(String[] args) throws InterruptedException {
        Demo d = new Demo();
        Thread t1 = new Thread(d);
        Thread t2 = new Thread(d);
        t1.start();
        t1.join();
        t2.start();
        for (int i = 0; i < 20; i++) {
            System.out.println(Thread.currentThread().getName()+"......"+i);
        }

    }
}

猜你喜欢

转载自www.cnblogs.com/hongxiao2020/p/12612163.html