有时候我们会遇到这样的场景,就是在某个线程执行完后,才能执行其它线程,基于这个那么如何让多个线程顺序执行呢?
现在有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
调用如下:
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
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....
推荐阅读
- Java|Java基础——数组
- 人工智能|干货!人体姿态估计与运动预测
- java简介|Java是什么(Java能用来干什么?)
- Java|规范的打印日志
- Linux|109 个实用 shell 脚本
- 程序员|【高级Java架构师系统学习】毕业一年萌新的Java大厂面经,最新整理
- Spring注解驱动第十讲--@Autowired使用
- SqlServer|sql server的UPDLOCK、HOLDLOCK试验
- jvm|【JVM】JVM08(java内存模型解析[JMM])
- 技术|为参加2021年蓝桥杯Java软件开发大学B组细心整理常见基础知识、搜索和常用算法解析例题(持续更新...)