Java 线程join()的用法

join()方法的作用,是等待这个线程结束;

也就是说,t.join()方法阻塞调用此方法的线程(calling thread)进入 TIMED_WAITING 状态,直到线程t完成,此线程再继续;

通常用于在main()主线程内,等待其它线程完成再结束main()主线程。

举个例子:

package reflection;

import java.util.Date;
import java.util.concurrent.TimeUnit;

public class Test01 implements Runnable {

private String name;

public Test01(String name) {
    this.name = name;
}

public void run() {
    System.out.printf("%s begins: %s\n", name, new Date());
    try {
        TimeUnit.SECONDS.sleep(4);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.printf("%s has finished: %s\n", name, new Date());
}

public static void main(String[] args) {
    Thread thread1 = new Thread(new Test01("One"));
    Thread thread2 = new Thread(new Test01("Two"));
    thread1.start();
    thread2.start();

    try {
        thread1.join();
        thread2.join();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    System.out.println("Main thread is finished");
}

}

结果为:
One begins: Wed Nov 27 10:45:24 CST 2019
Two begins: Wed Nov 27 10:45:24 CST 2019
One has finished: Wed Nov 27 10:45:28 CST 2019
Two has finished: Wed Nov 27 10:45:28 CST 2019
Main thread is finished

可见,thread.start()线程开始,thread.join()会使其他线程暂停,等待该线程结束后才会继续。main()主线程开始的最早,结束的最迟。

发布了35 篇原创文章 · 获赞 2 · 访问量 4428

猜你喜欢

转载自blog.csdn.net/weixin_41072132/article/details/103271386