1.

@Data
public abstract class BaseLatch {
private int limit;
protected int running; BaseLatch(int limit) {
this.limit = limit;
running = limit;
} public abstract void await() throws InterruptedException; public abstract void await(long ms) throws InterruptedException, TimeoutException; public abstract void countDown();
} class CountDownLatch extends BaseLatch { public CountDownLatch(int limit) {
super(limit);
} @Override
public void await() throws InterruptedException {
synchronized (this) {
while (this.running > 0) {
this.wait();
}
}
} @Override
public void await(long ms) throws InterruptedException, TimeoutException {
Assert.isTrue(ms > 0, "不允许小于0");
final long endTime = System.currentTimeMillis() + ms;
synchronized (this) {
while (this.running > 0) {
long balanceTime = endTime - System.currentTimeMillis();
if (balanceTime <= 0) {
throw new TimeoutException();
}
this.wait(balanceTime);
}
}
} @Override
public void countDown() {
synchronized (this) {
if (this.running <= 0) {
throw new IllegalStateException("");
}
this.running--;
this.notifyAll();
}
}
} class LatchTest {
public static void main(String[] args) throws InterruptedException {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Work<Integer>[] works = new Work[2];
BaseLatch latch = new CountDownLatch(works.length);
for (int i = 0; i < works.length; i++) {
works[i] = new Work<Integer>(latch);
new Thread(works[i]).start();
}
try {
latch.await(5000);
} catch (TimeoutException ex) { }
for (int i = 0; i < works.length; i++) {
System.out.println(works[i].getResult());
}
stopWatch.stop();
System.out.println("共消耗时间:" + stopWatch.getTotalTimeSeconds() + "秒");
}
} class Work<T> extends Thread {
private BaseLatch latch;
private T result; public Work(BaseLatch latch) {
this.latch = latch;
} @Override
public void run() {
try {
Random random = new Random();
int ms = random.nextInt(10) + 1;
Thread.sleep(1000 * ms);
this.result = (T) (Object) ms;
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
latch.countDown();
}
} public T getResult() {
return result;
}
}

2.可能的输出如下

null
2
共消耗时间:5.012秒

最新文章

  1. 【转】hive导入数据出现NULL
  2. synchronized四要素及抽象
  3. EF架构~对AutoMapper实体映射的扩展
  4. Python自动化之select、greenlet和gevent和事件驱动模型初探
  5. Jpinyin笔记
  6. python 字符串函数
  7. Python 之range 和 xrange
  8. 解决服务器断电导致mysql数据库无法启动
  9. [Linked List]Remove Duplicates from Sorted List
  10. jQuery动态添加元素事件
  11. FrameBuffer系列 之 简单编程
  12. awk内引用shell变量【自己手动加精】
  13. Spring集成RabbitMQ-使用RabbitMQ更方便
  14. tomcat的Jsp执行
  15. Linux&#160;学习笔记之超详细基础linux命令&#160;Part&#160;5
  16. UVa140 Bandwidth 【最优性剪枝】
  17. 关于IE和360安全浏览器如何添加百度搜索为默认的搜索引擎
  18. web03-OutputInfo
  19. 开源分布式工作流任务调度系统Easy Scheduler Release 1.0.2发布
  20. VS2017开发Linux平台上的程序

热门文章

  1. guestfish修改镜像内容
  2. 复杂HTML页面解析
  3. bean 的各个属性
  4. Linux上编译hadoop-2.7.1的libhdfs.so和libhdfs.a
  5. malloc.c
  6. B-spline Curves 学习之B样条曲线的导数(8)
  7. asp.net部署时加密config文件
  8. Git管理
  9. 查看JVM内存使用情况
  10. 自己从0开始学习Unity的笔记 IV (C#循环练习输出素数)