为什么Thread.join表现不正常

时间:2019-02-09 06:41:15

标签: java multithreading synchronization

我是线程概念的新手。我进行了此测试以了解联接的工作原理。假定join使调用线程等待,直到由join实例表示的线程终止。我有两个线程t1和t2。首先,t1呼叫加入,然后t2呼叫加入。我期望t1在t2开始之前完成,因为从主线程调用了join。我期望主线程从调用第一个联接的那一点开始等待。但这不是它的行为方式。 t1,t2和打印“ Thread”的行开始并行运行。既然应该等待t1完成,那么主线程如何管理打印并调用t2?

public static void main(String[] args) throws InterruptedException, ExecutionException  {

    Thread t1 = new Thread(new A());
    Thread t2 = new Thread (new B());

    t1.start();
    t2.start();

    t1.join();
    System.out.println("Thread");
    t2.join();

}

1 个答案:

答案 0 :(得分:4)

您以错误的顺序致电join。启动t1,然后调用join,以便主线程将等待t1死掉,然后启动t2

public static void main(String args[]) throws InterruptedException{
  Thread t1 = new Thread(() -> System.out.println("a"));
  Thread t2 = new Thread (() -> System.out.println("b"));

  t1.start();
  t1.join(); //main waits for t1 to finish
  System.out.println("Thread");
  t2.start();
  t2.join(); //main waits for t2 to finish
} 

输出:

a
Thread
b

在同时启动t1t2然后调用t1.join()时,主线程实际上正在等待t1终止,因此t1将执行直到完成为止,但是在后台t2已经开始执行,因此这就是为什么您看到两个线程并行运行的原因。

public static void main(String args[]) throws InterruptedException{
   Thread t1 = new Thread(() -> System.out.println("a"));
   Thread t2 = new Thread (() -> System.out.println("b"));

   t1.start(); //Started executing 
   t2.start(); //Started executing

   t1.join(); //main thread waiting for t1, but in the background t2 is also executing independently 
   System.out.println("Thread");
   t2.join(); //main again waiting for t2 to die
}