如何让线程A,B,C顺序执行

有时候我们会遇到这样的场景,就是在某个线程执行完后,才能执行其它线程,基于这个那么如何让多个线程顺序执行呢?
现在有A,B,C三个线程,那么怎样让A线程执行完后B执行最后C执行。
三个线程类如下:

class ThreadA implements Runnable{ @Override public void run() { // TODO Auto-generated method stub System.out.println("ThreadA "+Thread.currentThread().getName()+" Start...."); } }class ThreadB implements Runnable{ @Override public void run() { // TODO Auto-generated method stub System.out.println("ThreadB "+Thread.currentThread().getName()+" Start...."); } }class ThreadC implements Runnable{ @Override public void run() { // TODO Auto-generated method stub System.out.println("ThreadC "+Thread.currentThread().getName()+" Start...."); } }


  • 使用join
join作用是:如果某个线程调用join方法,优先执行完该线程,才能够执行其它线程。
调用如下:
Thread a = new Thread(new ThreadA(),"A"); Thread b = new Thread(new ThreadB(),"B"); Thread c = new Thread(new ThreadC(),"C"); a.start(); a.join(); b.start(); b.join(); c.start(); c.join();

输出:ThreadA A Start....ThreadB B Start....ThreadC C Start....
  • 使用单线程池
调用如下:

Thread a = new Thread(new ThreadA(),"A"); Thread b = new Thread(new ThreadB(),"B"); Thread c = new Thread(new ThreadC(),"C"); ExecutorService singlePool = Executors.newSingleThreadExecutor(); singlePool.submit(a); singlePool.submit(b); singlePool.submit(c); singlePool.shutdown(); //要关闭,要不然会一直等待线程

输出:ThreadA pool-1-thread-1 Start....ThreadB pool-1-thread-1 Start....ThreadC pool-1-thread-1 Start....
  • 使用CountDownLatch
可以把CountDownLatch看作是一个计数器,如果调用其await()方法,那么此对象就会一直处于等待状态,直到countDown为0,才会继续执行下去。
class Worker implements Runnable{ CountDownLatch c1; CountDownLatch c2; public Worker(CountDownLatch c1,CountDownLatch c2) { this.c1 = c1; this.c2 = c2; } @Override public void run() { // TODO Auto-generated method stub try { this.c1.await(); System.out.println("Thread "+Thread.currentThread().getName()+" Start...."); this.c2.countDown(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

调用如下:

CountDownLatch c1 = new CountDownLatch(0); CountDownLatch c2 = new CountDownLatch(1); CountDownLatch c3 = new CountDownLatch(1); Thread a = new Thread(new Worker(c1,c2),"A"); Thread b = new Thread(new Worker(c2,c3),"B"); Thread c = new Thread(new Worker(c3,c3),"C"); a.start(); b.start(); c.start();

【如何让线程A,B,C顺序执行】输出:Thread A Start....Thread B Start....Thread C Start....

    推荐阅读