【Java多线程系列四】控制线程执行顺序
2024-09-02 07:45:56
假设有线程1/线程2/线程3,线程3必须在线程1/线程2执行完成之后开始执行,有两种方式可实现
- Thread类的join方法:使宿主线程阻塞指定时间或者直到寄生线程执行完毕
- CountDownLatch类:指定计数器,当计数器清零即取消阻塞
package com.concurrent.test; import java.util.concurrent.CountDownLatch; import org.junit.Assert;
import org.junit.Test; /**
* 规定线程的执行顺序
*/
public class ThreadOrderTest { private long millisUnit = 1000;
private int count = 2; class ThreadOrder {
/*
* join方法使多个线程依次执行
*/
public long preserveOrderViaJoin() throws InterruptedException {
long startMillis = System.currentTimeMillis();
Thread tmp; for (int i = 0; i < count; i++) {
tmp = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(millisUnit);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "join-" + i);
tmp.start();
tmp.join();//不停地监测线程是否执行完成,执行完成才继续往下
}
return System.currentTimeMillis() - startMillis;
} /*
* CountdownLatch可同时阻塞多个线程,但它们可并发执行
*/
public long preserveOrderViaCountdownLatch() throws InterruptedException {
long startMillis = System.currentTimeMillis();
final CountDownLatch countDownLatch = new CountDownLatch(count);
for (int i = 0; i < count; i++) {
new Thread(new Runnable() { @Override
public void run() {
try {
Thread.sleep(millisUnit);
} catch (InterruptedException e) {
e.printStackTrace();
}
//只要计数器清零,等待的线程就可以开始执行,于是可以达到并发的效果
countDownLatch.countDown();
}
},"countDownLatch-" + i).start();
}
countDownLatch.await();
return System.currentTimeMillis() - startMillis; }
} @Test
public void testPreserveOrderViaJoin() throws InterruptedException {
ThreadOrder threadOrder = new ThreadOrder();
Assert.assertEquals(count, threadOrder.preserveOrderViaJoin() / millisUnit);
} @Test
public void testPreserveOrderViaCountdownLatch() throws InterruptedException {
ThreadOrder threadOrder = new ThreadOrder();
Assert.assertEquals(1, threadOrder.preserveOrderViaCountdownLatch() / millisUnit);
}
}
最新文章
- Connect() 2016 大会的主题 ---微软大法好
- Microsoft.Office.Interop.Word 创建word
- sqlyog不用密码登陆(强制取消)
- supervisor program配置实例
- 为什么构造器不能是abstract, static, final, native or synchronized的?
- 8 个必备的PHP功能开发
- WCF初探-21:WCF终结点(endpoint)
- Java8 如何进行stream reduce,collection操作
- 打造万能的ListView GridView 适配器
- Python学习入门基础教程(learning Python)--5.2 Python读文件基础
- clang: error: unable to execute command: Segmentation fault: 11
- Nginx是什么?Nginx介绍及Nginx的优点
- DataProtection设置问题引起不同ASP.NET Core站点无法共享用户验证Cookie
- kali安全工具
- 利用sdkman安装kotlin和java环境
- 使用python(command line)出现的ImportError: No module named &#39;xxx&#39;问题
- 虚拟机中实现Linux与Windows之间的文件传输
- 酷!美国国家安全局(NSA)开源了逆向工程工具 Ghidra
- 在VC6/VC2005下使程序直接具有XP风格(XP Style):
- mybatis由浅入深day02_8spring和mybatis整合