假设有线程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);
}
}

最新文章

  1. Connect() 2016 大会的主题 ---微软大法好
  2. Microsoft.Office.Interop.Word 创建word
  3. sqlyog不用密码登陆(强制取消)
  4. supervisor program配置实例
  5. 为什么构造器不能是abstract, static, final, native or synchronized的?
  6. 8 个必备的PHP功能开发
  7. WCF初探-21:WCF终结点(endpoint)
  8. Java8 如何进行stream reduce,collection操作
  9. 打造万能的ListView GridView 适配器
  10. Python学习入门基础教程(learning Python)--5.2 Python读文件基础
  11. clang: error: unable to execute command: Segmentation fault: 11
  12. Nginx是什么?Nginx介绍及Nginx的优点
  13. DataProtection设置问题引起不同ASP.NET Core站点无法共享用户验证Cookie
  14. kali安全工具
  15. 利用sdkman安装kotlin和java环境
  16. 使用python(command line)出现的ImportError: No module named &#39;xxx&#39;问题
  17. 虚拟机中实现Linux与Windows之间的文件传输
  18. 酷!美国国家安全局(NSA)开源了逆向工程工具 Ghidra
  19. 在VC6/VC2005下使程序直接具有XP风格(XP Style):
  20. mybatis由浅入深day02_8spring和mybatis整合

热门文章

  1. Python 定时任务框架 APScheduler 详解
  2. switch gnome-terminal tabs
  3. DNS域名解析服务以及Bind服务程序
  4. CF1220F
  5. 【牛客网-剑指offer】斐波拉契数列
  6. centos6.5大于2T容量硬盘分区、格式化、挂载!
  7. MHA + proxysql 高可用以及读写分离
  8. Codeforces 1148F Foo Fighters 贪心
  9. HDU 6326 Problem H Monster Hunter
  10. PHP多参数方法的重构