1.main线程中先调用threadA.join() ,再调用threadB.join()实现A->B->main线程的执行顺序

 调用threadA.join()时,main线程会挂起,等待threadA执行完毕返回后再执行,到执行threadB.join()时再挂起,待threadB执行完毕返回继续执行main

使用场景:线程B依赖线程A的计算结果的场景

package concurrency;

public class JoinTest {
    public static void main(String[] args) throws InterruptedException{
        Thread threadA = new Thread(new JoinJob(),"thread-A");
        Thread threadB = new Thread(new JoinJob(),"thread-B");
        threadB.start();
        threadA.start();
        threadA.join();
        threadB.join();
        
        System.out.println("main ending...");
    }
}

class JoinJob implements Runnable{
    
    @Override
    public void run() {
        System.err.println(Thread.currentThread().getName() + " starting...");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " ending...");
        
    }
    
}
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-05-19
  • 2022-01-10
  • 2022-12-23
  • 2022-01-29
  • 2021-11-03
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-01-07
  • 2022-01-21
  • 2021-04-13
  • 2021-06-14
  • 2022-12-23
  • 2021-06-25
相关资源
相似解决方案