关闭

初识java.util.concurrent.CyclicBarrier

49人阅读 评论(0) 收藏 举报
分类:
package learn;


import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;


public class CyclicBarrierDemo {
private static int num = 4;
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();


CyclicBarrier barrier = new CyclicBarrier(num, 
new Runnable(){
@Override
public void run() {
System.out.println("Go go go!");
service.shutdown();
}
}
);

for (int i = 0; i < num; i++)
{
service.submit(new Runnable(){
@Override
public void run() {
try {
Thread.sleep(ThreadLocalRandom.current().nextLong(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println(Thread.currentThread().getName() + " is here!");

try {
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
});
}
}
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:80次
    • 积分:20
    • 等级:
    • 排名:千里之外
    • 原创:2篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档