栅栏类似于闭锁,它能阻塞一组线程直到某个事件的发生。栅栏与闭锁的关键区别在于,所有的线程必须同时到达栅栏位置,才能继续执行。闭锁用于等待事件,而栅栏用于等待其他线程。
package com.example.demo.util.dxc; import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.FutureTask; /**
* 测试CyclicBarrier 循环栅栏
*/
public class TestCycliBarrier { public void test() throws Exception {
int threadNum = 10;
Integer total = 0;
CyclicBarrier cyclicBarrier1 = new CyclicBarrier(threadNum, new Runnable() {
//最后一个线程到栅栏后要做的任务
@Override
public void run() {
System.out.println("准备就绪,开始计算...");
}
});
List<FutureTask<Integer>> list = new ArrayList<>();
for (int j = 0; j < threadNum; j++) {
FutureTask<Integer> future = new FutureTask<Integer>(new MyCallThread(cyclicBarrier1));
Thread thread = new Thread(future);
thread.start();
list.add(future);
}
for (FutureTask<Integer> integerFutureTask : list) {
total += integerFutureTask.get();
}
System.out.println("计算结果:" + total);
} public static void main(String[] args) throws Exception {
new TestCycliBarrier().test();
} } package com.example.demo.util.dxc;
import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier; public class MyCallThread implements Callable<Integer> {
private CyclicBarrier cyclicBarrier; public MyCallThread(CyclicBarrier cyclicBarrier) {
this.cyclicBarrier = cyclicBarrier;
} @Override
public Integer call() throws Exception {
int num = 0;
for (int i = 0; i <= 100; i++) {
num += i;
}
System.out.println(Thread.currentThread().getName() + ":befor");
//等待所有线程到达之后才会返回num
cyclicBarrier.await();
System.out.println(Thread.currentThread().getName() + ":after");
return num;
}
}

最新文章

  1. runtime运行时
  2. (转)Learning to Rank for IR的评价指标—MAP,NDCG,MRR
  3. Hadoop2.0重启脚本
  4. [ZOJ 3631] Watashi&#39;s BG
  5. RedHat 6.5 离线安装 apache2.4.23
  6. 使用HTML5 Canvas做些什么
  7. 第1课 - 学习Lua的意义
  8. ElasticSearch5在Ubuntu系统下的安装和Java调用
  9. 【原码笔记】-- protobuf.js 与 Long.js
  10. Nginx学习笔记3--Nginx和PHP(fastCGI)的配置和优化
  11. Linux以百万兆字节显示内存大小
  12. SQLServer之存储过程简介
  13. 5、Docker容器网络
  14. javap -v没有显示LocalVaribleTable
  15. centos下问题:connect:network is unreachable
  16. API判断本机安装的Revit版本信息
  17. [GPU] DIY for Deep Learning Workstation
  18. BP
  19. oracle 实例名,数据库名概念
  20. 第一章:什么是Linux

热门文章

  1. laravel Route::resource() 资源路由
  2. linux命令--truncate 学习
  3. nginx检查报错:nginx: [emerg] &quot;server&quot; directive is not allowed here in
  4. leetcode-mid-dynamic programming-322. Coin Change - NO
  5. Hook基本知识
  6. 通过同步上下文方式更新winform中的控件信息
  7. 安装ubuntu双系统
  8. spotlight监控linux性能
  9. Text Elements(文本元素)对象
  10. Java面试题集(131-135)