1、利用线程的join方法,暂停正在运行的线程,执行调用join的线程。强制参与进来。
private static void testMethod1(){
Thread threadA = new Thread(() -> System.out.println("A"));
Thread threadB = new Thread(() -> System.out.println("B"));
Thread threadC = new Thread(() -> System.out.println("C"));
try {
threadA.start();
threadA.join();
threadB.start();
threadB.join();
threadC.start();
threadC.join();
}catch (Exception e){
e.printStackTrace();
}
}
2、利用线程池的特性,这里是利用了核心线程数和最大线程数为1以及等待队列有序的特性,线程池中只存在一个线程,后加进来的两个线程都在进入等待队列中,按顺序进入。当线程A的任务执行完成,B任务进入,最后C任务进入。
private static void testMethod2(){
Thread threadA = new Thread(() -> System.out.println("A"));
Thread threadB = new Thread(() -> System.out.println("B"));
Thread threadC = new Thread(() -> System.out.println("C"));
ThreadPoolExecutor threadExecutor = new ThreadPoolExecutor(1,1,1000, TimeUnit.SECONDS,new ArrayBlockingQueue<>(10),new ThreadPoolExecutor.AbortPolicy());
threadExecutor.execute(threadA);
threadExecutor.execute(threadB);
threadExecutor.execute(threadC);
threadExecutor.shutdown();
}
3、两者的实现效果: