本文整理了Java中java.util.concurrent.CyclicBarrier.<init>()
方法的一些代码示例,展示了CyclicBarrier.<init>()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。CyclicBarrier.<init>()
方法的具体详情如下:
包路径:java.util.concurrent.CyclicBarrier
类名称:CyclicBarrier
方法名:<init>
[英]Creates a new CyclicBarrier that will trip when the given number of parties (threads) are waiting upon it, and does not perform a predefined action when the barrier is tripped.
[中]创建一个新的CyclicBarrier,当给定数量的参与方(线程)正在等待它时,它将跳闸,并且在屏障跳闸时不执行预定义的操作。
代码示例来源:origin: stackoverflow.com
private CyclicBarrier barrier = new CyclicBarrier(2);
void main() throws InterruptedException{
asyncDoSomething();
//wait until other party calls barrier.await()
barrier.await();
}
void onFinishDoSomething() throws InterruptedException{
//do something ...
//then signal the end of work
barrier.await();
}
代码示例来源:origin: stackoverflow.com
// We want to start just 2 threads at the same time, but let's control that
// timing from the main thread. That's why we have 3 "parties" instead of 2.
final CyclicBarrier gate = new CyclicBarrier(3);
Thread t1 = new Thread(){
public void run(){
gate.await();
//do stuff
}};
Thread t2 = new Thread(){
public void run(){
gate.await();
//do stuff
}};
t1.start();
t2.start();
// At this point, t1 and t2 are blocking on the gate.
// Since we gave "3" as the argument, gate is not opened yet.
// Now if we block on the gate from the main thread, it will open
// and all threads will start to do stuff!
gate.await();
System.out.println("all threads started");
代码示例来源:origin: LeonardoZ/java-concurrency-patterns
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
Runnable barrierAction = () -> System.out.println("Well done, guys!");
CyclicBarrier barrier = new CyclicBarrier(10, barrierAction);
Runnable task = () -> {
try {
// simulating a task that can take at most 1sec to run
System.out.println("Doing task for " + Thread.currentThread().getName());
Thread.sleep(new Random().nextInt(10) * 100);
System.out.println("Done for " + Thread.currentThread().getName());
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
};
for (int i = 0; i < 10; i++) {
executor.execute(task);
}
executor.shutdown();
}
代码示例来源:origin: killme2008/Metamorphosis
public void start() {
this.barrier = new CyclicBarrier(this.threadCount + 1, this.watch);
for (int i = 0; i < this.threadCount; i++) {
new Thread(new ConcurrentTestRunner(this.barrier, this.task, this.repeatCount, i)).start();
}
try {
this.watch.start();
this.barrier.await();
this.barrier.await();
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
代码示例来源:origin: wildfly/wildfly
protected void sendMessages() {
final AtomicInteger num_msgs_sent=new AtomicInteger(0); // all threads will increment this
final AtomicInteger actually_sent=new AtomicInteger(0); // incremented *after* sending a message
final AtomicLong seqno=new AtomicLong(1); // monotonically increasing seqno, to be used by all threads
final Sender[] senders=new Sender[num_threads];
final CyclicBarrier barrier=new CyclicBarrier(num_threads +1);
final byte[] payload=new byte[msg_size];
for(int i=0; i < num_threads; i++) {
senders[i]=new Sender(barrier, num_msgs_sent, actually_sent, seqno, payload);
senders[i].setName("sender-" + i);
senders[i].start();
}
try {
System.out.printf("-- sending %,d %s\n", num_msgs, (oob? " OOB msgs" : " msgs"));
barrier.await();
}
catch(Exception e) {
System.err.println("failed triggering send threads: " + e);
}
}
代码示例来源:origin: wildfly/wildfly
protected void sendMessages() {
final AtomicInteger num_msgs_sent=new AtomicInteger(0); // all threads will increment this
final AtomicLong seqno=new AtomicLong(1); // monotonically increasing seqno, to be used by all threads
final Sender[] senders=new Sender[num_threads];
final CyclicBarrier barrier=new CyclicBarrier(num_threads +1);
final byte[] payload=new byte[msg_size];
for(int i=0; i < num_threads; i++) {
senders[i]=new Sender(barrier, num_msgs_sent, seqno, payload);
senders[i].setName("invoker-" + i);
senders[i].start();
}
try {
System.out.println("-- invoking " + num_msgs + " msgs");
barrier.await();
}
catch(Exception e) {
System.err.println("failed triggering send threads: " + e);
}
}
代码示例来源:origin: wildfly/wildfly
protected void sendMessages() {
final AtomicInteger num_msgs_sent=new AtomicInteger(0); // all threads will increment this
final Sender[] senders=new Sender[num_threads];
final CyclicBarrier barrier=new CyclicBarrier(num_threads +1);
final byte[] payload=new byte[msg_size];
reset();
for(int i=0; i < num_threads; i++) {
senders[i]=new Sender(barrier, num_msgs_sent, payload);
senders[i].setName("sender-" + i);
senders[i].start();
}
try {
System.out.println("-- sending " + num_msgs + " msgs");
barrier.await();
}
catch(Exception e) {
System.err.println("failed triggering send threads: " + e);
}
}
代码示例来源:origin: LMAX-Exchange/disruptor
private Future<List<StubEvent>> getMessages(final long initial, final long toWaitFor) throws InterruptedException,
BrokenBarrierException
{
final CyclicBarrier cyclicBarrier = new CyclicBarrier(2);
final SequenceBarrier sequenceBarrier = ringBuffer.newBarrier();
final Future<List<StubEvent>> f = executor.submit(
new TestWaiter(
cyclicBarrier, sequenceBarrier, ringBuffer,
initial, toWaitFor));
cyclicBarrier.await();
return f;
}
代码示例来源:origin: google/guava
public void testCustomSchedule_startStop() throws Exception {
final CyclicBarrier firstBarrier = new CyclicBarrier(2);
final CyclicBarrier secondBarrier = new CyclicBarrier(2);
final AtomicBoolean shouldWait = new AtomicBoolean(true);
Runnable task =
new Runnable() {
@Override
public void run() {
try {
if (shouldWait.get()) {
firstBarrier.await();
secondBarrier.await();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
};
TestCustomScheduler scheduler = new TestCustomScheduler();
Future<?> future = scheduler.schedule(null, Executors.newScheduledThreadPool(10), task);
firstBarrier.await();
assertEquals(1, scheduler.scheduleCounter.get());
secondBarrier.await();
firstBarrier.await();
assertEquals(2, scheduler.scheduleCounter.get());
shouldWait.set(false);
secondBarrier.await();
future.cancel(false);
}
代码示例来源:origin: google/guava
public void testTaskThrowsError() throws Exception {
class MyError extends Error {}
final CyclicBarrier barrier = new CyclicBarrier(2);
barrier.await(1, TimeUnit.SECONDS);
executor.execute(barrierTask);
barrier.await(1, TimeUnit.SECONDS);
} finally {
service.shutdown();
代码示例来源:origin: google/guava
final CyclicBarrier barrier = new CyclicBarrier(numThreads + 1);
Runnable wrapper =
new Runnable() {
executor.execute(wrapper);
barrier.await(); // release the threads!
barrier.await(); // wait for them all to complete
assertEquals(1, task.get().intValue());
assertEquals(1, counter.get());
代码示例来源:origin: google/guava
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();
}
}
代码示例来源:origin: Netflix/servo
@Test
public void testConcurrentTagList() throws Exception {
final int count = 10;
final CountDownLatch latch = new CountDownLatch(count);
final Set<BasicTagList> tagLists = Collections
.newSetFromMap(new ConcurrentHashMap<>());
final CyclicBarrier barrier = new CyclicBarrier(count);
for (int i = 0; i < count; i++) {
new Thread(() -> {
try {
barrier.await();
tagLists.add(BasicTagList.of("id", "1", "color",
"green"));
} catch (Exception e) {
e.printStackTrace(System.out);
} finally {
latch.countDown();
}
}).start();
}
latch.await();
assertEquals(tagLists.size(), 1);
}
}
代码示例来源:origin: apache/pulsar
final CyclicBarrier barrier = new CyclicBarrier(Consumers + 1);
barrier.await();
for (int i = 0; i < Messages; i++) {
ledger.addEntry("test".getBytes());
代码示例来源:origin: google/guava
public void testDirectExecutorServiceServiceTermination() throws Exception {
final ExecutorService executor = newDirectExecutorService();
final CyclicBarrier barrier = new CyclicBarrier(2);
final AtomicReference<Throwable> throwableFromOtherThread = new AtomicReference<>(null);
final Runnable doNothingRunnable =
barrier.await(1, TimeUnit.SECONDS);
assertFalse(executor.isShutdown());
assertFalse(executor.isTerminated());
barrier.await(1, TimeUnit.SECONDS);
assertFalse(executor.awaitTermination(20, TimeUnit.MILLISECONDS));
barrier.await(1, TimeUnit.SECONDS);
assertTrue(executor.awaitTermination(1, TimeUnit.SECONDS));
assertTrue(executor.awaitTermination(0, TimeUnit.SECONDS));
代码示例来源:origin: apache/ignite
/**
*
*/
@Test
public void testDoInParallel() throws Throwable {
CyclicBarrier barrier = new CyclicBarrier(3);
ExecutorService executorService = Executors.newFixedThreadPool(3);
try {
IgniteUtils.doInParallel(3,
executorService,
asList(1, 2, 3),
i -> {
try {
barrier.await(1, TimeUnit.SECONDS);
}
catch (Exception e) {
throw new IgniteCheckedException(e);
}
return null;
}
);
} finally {
executorService.shutdownNow();
}
}
代码示例来源:origin: ehcache/ehcache3
@Test
public void CachingTierDoesNotSeeAnyOperationDuringClear() throws StoreAccessException, BrokenBarrierException, InterruptedException {
final TieredStore<String, String> tieredStore = new TieredStore<>(stringCachingTier, stringAuthoritativeTier);
final CyclicBarrier barrier = new CyclicBarrier(2);
doAnswer((Answer<Void>) invocation -> {
barrier.await();
barrier.await();
return null;
}).when(stringAuthoritativeTier).clear();
Thread t = new Thread(() -> {
try {
tieredStore.clear();
} catch (Exception e) {
throw new RuntimeException(e);
}
});
t.start();
barrier.await();
tieredStore.get("foo");
barrier.await();
t.join();
verify(stringCachingTier, never()).getOrComputeIfAbsent(
ArgumentMatchers.any(), ArgumentMatchers.any());
}
代码示例来源:origin: apache/pulsar
final CyclicBarrier barrier = new CyclicBarrier(Threads);
final CountDownLatch counter = new CountDownLatch(Threads);
final AtomicBoolean gotException = new AtomicBoolean(false);
cachedExecutor.execute(() -> {
try {
barrier.await();
代码示例来源:origin: ReactiveX/RxJava
@Test(timeout = 5000)
public void testConcurrentSizeAndHasAnyValueBounded() throws InterruptedException {
final ReplayProcessor<Object> rs = ReplayProcessor.createWithSize(3);
final CyclicBarrier cb = new CyclicBarrier(2);
t.start();
try {
cb.await();
} catch (InterruptedException e) {
return;
代码示例来源:origin: apache/incubator-druid
Assert.assertFalse(q.offer(obj, delayMS, TimeUnit.MILLISECONDS));
Assert.assertFalse(q.offer(obj));
final CyclicBarrier barrier = new CyclicBarrier(2);
barrier.await();
q.take();
barrier.await();
q.take();
Assert.assertTrue(future.get());
内容来源于网络,如有侵权,请联系作者删除!