简体   繁体   English

为什么Thread.join表现不正常

[英]Why is Thread.join not behaving as expected

I am new to the concept of threads. 我是线程概念的新手。 I made this test to understand how join works. 我进行了此测试以了解联接的工作原理。 join is suppose to cause the calling thread to wait until the thread represented by the join instance terminates. 假定join使调用线程等待,直到由join实例表示的线程终止。 I have two threads t1 and t2. 我有两个线程t1和t2。 First, t1 calls join and then t2 calls join. 首先,t1呼叫加入,然后t2呼叫加入。 I was expecting for t1 to finish before t2 starts since join is called from with the main thread. 我期望t1在t2开始之前完成,因为从主线程调用了join。 I was expecting the main thread to wait from the point where the first join is called. 我期望主线程从调用第一个联接的那一点开始等待。 But that is not how it behaves. 但这不是它的行为方式。 t1, t2 and the line that prints "Thread" starts running in parallel. t1,t2和打印“ Thread”的行开始并行运行。 How did the main thread manage to print and call t2 since it was suppose to be waiting for t1 to finishes? 由于假定等待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();

}

You are calling join in the wrong order. 您以错误的顺序呼叫join Start t1 and then call join so that the main thread will wait for t1 to die then start t2 . 启动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
} 

Output: 输出:

a
Thread
b

When you are starting both t1 and t2 and then calling t1.join() the main thread is indeed waiting for t1 to die, so t1 will execute till it finishes but in the background t2 has already started executing so that is why you see both threads are running in parallel. 当您同时启动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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM