1、通过join()方法使当前线程“阻塞”。等待指定线程执行完毕后继续执行。举例:在线程thread2中,加上一句thread1.join(),其意义在于,当前线程2运行到此行代码时会进入阻塞状态,直到线程thread1执行完毕后,线程thread2才会继续运行,这就保证了线程thread1与线程thread2的运行顺序。
或者我们可以在main函数中通过join()方法让主线程阻塞等待以达到指定顺序执行的目的。
thread1.start();
thread1.join();
thread2.start();
thread2.join();
thread3.start();
2、单线程化线程池(newSingleThreadExecutor)的优点,串行执行所有任务。
static
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit(thread1);
executorService.submit(thread2);
executorService.submit(thread3);
executorService.shutdown();