标签:exception ati util sof baidu ... mat tac author
事例:
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();
}
}
标签:exception ati util sof baidu ... mat tac author
原文地址:http://www.cnblogs.com/wanglaicai/p/6384495.html