本文整理汇总了Java中java.util.concurrent.CyclicBarrier类的典型用法代码示例。如果您正苦于以下问题:Java CyclicBarrier类的具体用法?Java CyclicBarrier怎么用?Java CyclicBarrier使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
CyclicBarrier类属于java.util.concurrent包,在下文中一共展示了CyclicBarrier类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: main
import java.util.concurrent.CyclicBarrier; //导入依赖的package包/类
/**
* 版本3.0.9以下存在多线程初始化问题,这个类作为一个样例
*/
public static void main(String[] args) throws InterruptedException, BrokenBarrierException {
System.out.println(Arrays.asList(splitWord));
for (int j = 0; j < 1000; j++) {
CyclicBarrier barrier = new CyclicBarrier(11, null);
for (int i = 0; i < 10; i++) {
Thread t = new Thread(new Worker(barrier), "t" + i);
t.start();
}
Thread.sleep(500);
barrier.await();
while (barrier.getNumberWaiting() > 0) {
Thread.sleep(1000);
}
Thread.sleep(1000);
System.out.println(Arrays.asList(splitWord));
}
}
示例2: ThreadCommSlave
import java.util.concurrent.CyclicBarrier; //导入依赖的package包/类
/**
* Process communication constructor, every process have just only one ThreadCommSlave instance.
* @param loginName if you use ssh to execute command, you must provide login name, e.g. ssh [email protected] "your command"
* @param threadNum thread number in each process.
* @param masterHost master host name
* @param masterPort master host port
* @throws Mp4jException
*/
public ThreadCommSlave(String loginName, int threadNum, String masterHost, int masterPort) throws Mp4jException {
this.threadNum = threadNum;
this.barrier = new CyclicBarrier(threadNum);
try {
processCommSlave = new ProcessCommSlave(loginName, masterHost, masterPort);
this.rank = processCommSlave.getRank();
this.slaveNum = processCommSlave.getSlaveNum();
this.threadBQueues = new LinkedBlockingDeque[threadNum];
for (int t = 0; t < threadNum; t++) {
this.threadBQueues[t] = new LinkedBlockingDeque<>();
}
} catch (Exception e) {
throw new Mp4jException(e);
}
}
示例3: testReset_NoBrokenBarrier
import java.util.concurrent.CyclicBarrier; //导入依赖的package包/类
/**
* A reset before threads enter barrier does not throw
* BrokenBarrierException
*/
public void testReset_NoBrokenBarrier() throws Exception {
final CyclicBarrier c = new CyclicBarrier(3);
c.reset();
Thread t1 = newStartedThread(new CheckedRunnable() {
public void realRun() throws Exception {
c.await();
}});
Thread t2 = newStartedThread(new CheckedRunnable() {
public void realRun() throws Exception {
c.await();
}});
c.await();
awaitTermination(t1);
awaitTermination(t2);
}
示例4: testCommitJobFailsJob
import java.util.concurrent.CyclicBarrier; //导入依赖的package包/类
@Test(timeout=20000)
public void testCommitJobFailsJob() throws Exception {
Configuration conf = new Configuration();
conf.set(MRJobConfig.MR_AM_STAGING_DIR, stagingDir);
AsyncDispatcher dispatcher = new AsyncDispatcher();
dispatcher.init(conf);
dispatcher.start();
CyclicBarrier syncBarrier = new CyclicBarrier(2);
OutputCommitter committer = new TestingOutputCommitter(syncBarrier, false);
CommitterEventHandler commitHandler =
createCommitterEventHandler(dispatcher, committer);
commitHandler.init(conf);
commitHandler.start();
JobImpl job = createRunningStubbedJob(conf, dispatcher, 2, null);
completeJobTasks(job);
assertJobState(job, JobStateInternal.COMMITTING);
// let the committer fail and verify the job fails
syncBarrier.await();
assertJobState(job, JobStateInternal.FAILED);
dispatcher.stop();
commitHandler.stop();
}
示例5: main
import java.util.concurrent.CyclicBarrier; //导入依赖的package包/类
public static void main(String[] args) throws InterruptedException {
final int N=10;
Thread[] allSoldier=new Thread[N];
boolean flag=false;
CyclicBarrier cyclic=new CyclicBarrier(N,new BarrierRun(flag,N));
System.out.println("集合队伍!");
for(int i=0;i<N;++i){
System.out.println("士兵 "+i+"报道!");
allSoldier[i]=new Thread(new Soldier(cyclic,"士兵"+i));
allSoldier[i].start();
// if(i==5) {这个中断会引起一个interrupt()和n个BrokenBarrierException异常。意思是栅栏破坏掉了,
// 线程永远无法完成栅栏
// allSoldier[1].interrupt();
// }
}
}
示例6: blockExecutor
import java.util.concurrent.CyclicBarrier; //导入依赖的package包/类
/**
* Blocks the named executor by getting its only thread running a task blocked on a CyclicBarrier and fills the queue with a noop task.
* So requests to use this queue should get {@link EsRejectedExecutionException}s.
*/
private CyclicBarrier blockExecutor(String name) throws Exception {
ThreadPool threadPool = getInstanceFromNode(ThreadPool.class);
CyclicBarrier barrier = new CyclicBarrier(2);
logger.info("Blocking the [{}] executor", name);
threadPool.executor(name).execute(() -> {
try {
threadPool.executor(name).execute(() -> {});
barrier.await();
logger.info("Blocked the [{}] executor", name);
barrier.await();
logger.info("Unblocking the [{}] executor", name);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
barrier.await();
blockedExecutors.add(barrier);
return barrier;
}
示例7: testCustomScheduler_deadlock
import java.util.concurrent.CyclicBarrier; //导入依赖的package包/类
public void testCustomScheduler_deadlock() throws InterruptedException, BrokenBarrierException {
final CyclicBarrier inGetNextSchedule = new CyclicBarrier(2);
// This will flakily deadlock, so run it multiple times to increase the flake likelihood
for (int i = 0; i < 1000; i++) {
Service service = new AbstractScheduledService() {
@Override protected void runOneIteration() {}
@Override protected Scheduler scheduler() {
return new CustomScheduler() {
@Override protected Schedule getNextSchedule() throws Exception {
if (state() != State.STARTING) {
inGetNextSchedule.await();
Thread.yield();
throw new RuntimeException("boom");
}
return new Schedule(0, TimeUnit.NANOSECONDS);
}
};
}
};
service.startAsync().awaitRunning();
inGetNextSchedule.await();
service.stopAsync();
}
}
示例8: test
import java.util.concurrent.CyclicBarrier; //导入依赖的package包/类
static void test(int i, int nkeys, String[] key, Class mapClass) throws Exception {
System.out.print("Threads: " + i + "\t:");
Map map = (Map) mapClass.newInstance();
// Uncomment to start with a non-empty table
// for (int j = 0; j < nkeys; j += 4) // start 1/4 occupied
// map.put(key[j], key[j]);
LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
CyclicBarrier barrier = new CyclicBarrier(i + 1, timer);
for (int t = 0; t < i; ++t)
pool.execute(new Runner(t, map, key, barrier));
barrier.await();
barrier.await();
long time = timer.getTime();
long tpo = time / (i * (long) nops);
System.out.print(LoopHelpers.rightJustify(tpo) + " ns per op");
double secs = (double) (time) / 1000000000.0;
System.out.println("\t " + secs + "s run time");
map.clear();
}
示例9: SomeFeed
import java.util.concurrent.CyclicBarrier; //导入依赖的package包/类
private SomeFeed(int threadCount, boolean barriered) {
this.threadCount = threadCount;
this.barriered = barriered;
if (barriered) {
barrier = new CyclicBarrier(threadCount, System.out::println);
}
launchPublishers();
SomeListener tickOutputter = new SomeListener() {
@Override
public void priceTick(PriceTick event) {
System.out.println(".");
}
@Override
public void error(Throwable throwable) {
}
};
// register(tickOutputter);
}
示例10: SimpleProcessorBenchmarkClientRunnable
import java.util.concurrent.CyclicBarrier; //导入依赖的package包/类
public SimpleProcessorBenchmarkClientRunnable(String targetIP, int targetPort, int clientNums, int rpcTimeout,
CyclicBarrier barrier, CountDownLatch latch, long startTime,
long endTime){
this.targetIP = targetIP;
this.targetPort = targetPort;
this.clientNums = clientNums;
this.rpcTimeout = rpcTimeout;
this.barrier = barrier;
this.latch = latch;
this.startTime = startTime;
this.endTime = endTime;
maxRange = (Integer.parseInt(String.valueOf((endTime - startTime))) / 1000) + 1;
errorTPS = new long[maxRange];
errorResponseTimes = new long[maxRange];
tps = new long[maxRange];
responseTimes = new long[maxRange];
// init
for (int i = 0; i < maxRange; i++) {
errorTPS[i] = 0;
errorResponseTimes[i] = 0;
tps[i] = 0;
responseTimes[i] = 0;
}
}
示例11: testAddAndSumMT
import java.util.concurrent.CyclicBarrier; //导入依赖的package包/类
/**
* adds by multiple threads produce correct sum
*/
public void testAddAndSumMT() throws Throwable {
final int incs = 1000000;
final int nthreads = 4;
final ExecutorService pool = Executors.newCachedThreadPool();
LongAdder a = new LongAdder();
CyclicBarrier barrier = new CyclicBarrier(nthreads + 1);
for (int i = 0; i < nthreads; ++i)
pool.execute(new AdderTask(a, barrier, incs));
barrier.await();
barrier.await();
long total = (long)nthreads * incs;
long sum = a.sum();
assertEquals(sum, total);
pool.shutdown();
}
示例12: eachThreadGetsDifferentGlobalTxId
import java.util.concurrent.CyclicBarrier; //导入依赖的package包/类
@Test
public void eachThreadGetsDifferentGlobalTxId() throws Exception {
CyclicBarrier barrier = new CyclicBarrier(2);
Runnable runnable = exceptionalRunnable(() -> {
String txId = UUID.randomUUID().toString();
omegaContext.setGlobalTxId(txId);
barrier.await();
assertThat(omegaContext.globalTxId(), is(txId));
});
CompletableFuture<Void> future1 = CompletableFuture.runAsync(runnable);
CompletableFuture<Void> future2 = CompletableFuture.runAsync(runnable);
CompletableFuture.allOf(future1, future2).join();
}
示例13: invokeEitherPostInterceptOrOnTimeoutConcurrently
import java.util.concurrent.CyclicBarrier; //导入依赖的package包/类
@Test(timeout = 5000)
public void invokeEitherPostInterceptOrOnTimeoutConcurrently() throws Exception {
List<Future<?>> futures = new LinkedList<>();
for (int i = 0; i < runningCounts; i++) {
TimeAwareInterceptor interceptor = new TimeAwareInterceptor(underlying);
CyclicBarrier cyclicBarrier = new CyclicBarrier(2);
futures.add(executorService.submit(() -> {
waitForSignal(cyclicBarrier);
interceptor.postIntercept(localTxId, signature);
}));
futures.add(executorService.submit(() -> {
waitForSignal(cyclicBarrier);
interceptor.onTimeout(localTxId, signature, timeoutException);
}));
}
waitTillAllDone(futures);
assertThat(postInterceptInvoked.get() + onTimeoutInvoked.get(), is(runningCounts));
}
示例14: invokeEitherOnErrorOrOnTimeoutConcurrently
import java.util.concurrent.CyclicBarrier; //导入依赖的package包/类
@Test(timeout = 5000)
public void invokeEitherOnErrorOrOnTimeoutConcurrently() throws Exception {
RuntimeException oops = new RuntimeException("oops");
List<Future<?>> futures = new LinkedList<>();
for (int i = 0; i < runningCounts; i++) {
TimeAwareInterceptor interceptor = new TimeAwareInterceptor(underlying);
CyclicBarrier cyclicBarrier = new CyclicBarrier(2);
futures.add(executorService.submit(() -> {
waitForSignal(cyclicBarrier);
interceptor.onError(localTxId, signature, oops);
}));
futures.add(executorService.submit(() -> {
waitForSignal(cyclicBarrier);
interceptor.onTimeout(localTxId, signature, timeoutException);
}));
}
waitTillAllDone(futures);
assertThat(onErrorInvoked.get() + onTimeoutInvoked.get(), is(runningCounts));
}
示例15: AbstractClientRunnable
import java.util.concurrent.CyclicBarrier; //导入依赖的package包/类
public AbstractClientRunnable(String targetIP, int targetPort, int clientNums, int rpcTimeout,
CyclicBarrier barrier, CountDownLatch latch, long startTime, long endTime){
this.barrier = barrier;
this.latch = latch;
this.startTime = startTime;
this.endTime = endTime;
serviceFactory.setTargetIP(targetIP);
serviceFactory.setClientNums(clientNums);
serviceFactory.setTargetPort(targetPort);
serviceFactory.setConnectTimeout(rpcTimeout);
maxRange = (Integer.parseInt(String.valueOf((endTime - startTime))) / 1000000) + 1;
errorTPS = new long[maxRange];
errorResponseTimes = new long[maxRange];
tps = new long[maxRange];
responseTimes = new long[maxRange];
// init
for (int i = 0; i < maxRange; i++) {
errorTPS[i] = 0;
errorResponseTimes[i] = 0;
tps[i] = 0;
responseTimes[i] = 0;
}
}