码迷,mamicode.com
首页 > 编程语言 > 详细

多线程的同步工具(CyclicBarrier)

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

标签:exception   ati   util   sof   baidu   ...   mat   tac   author   

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)

标签:exception   ati   util   sof   baidu   ...   mat   tac   author   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!