多线程的同步工具(CyclicBarrier)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程的同步工具(CyclicBarrier)相关的知识,希望对你有一定的参考价值。
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)的主要内容,如果未能解决你的问题,请参考以下文章
JAVA多线程提高十:同步工具CyclicBarrier与CountDownLatch
Java多线程工具包java.util.concurrent---CyclicBarrier