首页 > 编程语言 > 详细

多线程的同步工具(CyclicBarrier)

时间:2017-02-09 23:50:10      阅读:268      评论:0      收藏:0      [点我收藏+]

public class CyclicBarrierextends Object

事例:

package org.wangyi.tool;

import java.util.Base64;
import java.util.Random;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
* 线程障碍器
*
* @author wangyi
* @version 1.0 <br />
* <a href="www.baidu.com">百度一下</a>
*/
public class CyclicBarrierTest {
public static void main(String[] args) {
ExecutorService threadpool = Executors.newCachedThreadPool();
final CyclicBarrier cb = new CyclicBarrier(3);
for (int i = 0; i < 3; i++) {
Runnable runnable = new Runnable() {
@Override
public void run() {
try {

Thread.sleep((long) (Math.random() * 10000));
System.out.println("线程"
+ Thread.currentThread().getName()
+ "即将到达饭点1看,当前已有 "
+ (cb.getNumberWaiting() + 1)
+ "个已经到达,"
+ (cb.getNumberWaiting() == 2 ? "人来起了,开饭了!"
: "等候其他人..."));
cb.await();
Thread.sleep((long) (Math.random() * 10000));
System.out.println("线程"
+ Thread.currentThread().getName()
+ "即将到达饭点2看,当前已有 "
+ (cb.getNumberWaiting() + 1)
+ "个已经到达,"
+ (cb.getNumberWaiting() == 2 ? "人来起了,开饭了!"
: "等候其他人..."));
cb.await();
Thread.sleep((long) (Math.random() * 10000));
System.out.println("线程"
+ Thread.currentThread().getName()
+ "即将到达饭点3看,当前已有 "
+ (cb.getNumberWaiting() + 1)
+ "个已经到达,"
+ (cb.getNumberWaiting() == 2 ? "人来起了,开饭了!"
: "等候其他人..."));
cb.await();

} catch (Exception e) {
e.printStackTrace();
}
}
};
threadpool.execute(runnable);
}
threadpool.shutdown();

}

}

多线程的同步工具(CyclicBarrier)

原文:http://www.cnblogs.com/wanglaicai/p/6384495.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!