简体   繁体   中英

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. I have two threads t1 and t2. First, t1 calls join and then t2 calls join. I was expecting for t1 to finish before t2 starts since join is called from with the main thread. 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. How did the main thread manage to print and call t2 since it was suppose to be waiting for t1 to finishes?

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. Start t1 and then call join so that the main thread will wait for t1 to die then start 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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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