当前位置: 首页>>代码示例>>Java>>正文


Java CountDownLatch.countDown方法代码示例

本文整理汇总了Java中java.util.concurrent.CountDownLatch.countDown方法的典型用法代码示例。如果您正苦于以下问题:Java CountDownLatch.countDown方法的具体用法?Java CountDownLatch.countDown怎么用?Java CountDownLatch.countDown使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.util.concurrent.CountDownLatch的用法示例。


在下文中一共展示了CountDownLatch.countDown方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: testPullMessage_SuccessWithOrderlyService

import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
@Test
public void testPullMessage_SuccessWithOrderlyService() throws Exception {
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    final MessageExt[] messageExts = new MessageExt[1];

    MessageListenerOrderly listenerOrderly = new MessageListenerOrderly() {
        @Override
        public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) {
            messageExts[0] = msgs.get(0);
            countDownLatch.countDown();
            return null;
        }
    };
    pushConsumer.registerMessageListener(listenerOrderly);
    pushConsumer.getDefaultMQPushConsumerImpl().setConsumeMessageService(new ConsumeMessageOrderlyService(pushConsumer.getDefaultMQPushConsumerImpl(), listenerOrderly));
    pushConsumer.getDefaultMQPushConsumerImpl().setConsumeOrderly(true);
    pushConsumer.getDefaultMQPushConsumerImpl().doRebalance();
    PullMessageService pullMessageService = mQClientFactory.getPullMessageService();
    pullMessageService.executePullRequestLater(createPullRequest(), 100);

    countDownLatch.await(10, TimeUnit.SECONDS);
    assertThat(messageExts[0].getTopic()).isEqualTo(topic);
    assertThat(messageExts[0].getBody()).isEqualTo(new byte[] {'a'});
}
 
开发者ID:lyy4j,项目名称:rmq4note,代码行数:25,代码来源:DefaultMQPushConsumerTest.java

示例2: testSignalAll

import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
public void testSignalAll(boolean fair, final AwaitMethod awaitMethod) {
    final PublicReentrantLock lock = new PublicReentrantLock(fair);
    final Condition c = lock.newCondition();
    final CountDownLatch pleaseSignal = new CountDownLatch(2);
    class Awaiter extends CheckedRunnable {
        public void realRun() throws InterruptedException {
            lock.lock();
            pleaseSignal.countDown();
            await(c, awaitMethod);
            lock.unlock();
        }
    }

    Thread t1 = newStartedThread(new Awaiter());
    Thread t2 = newStartedThread(new Awaiter());

    await(pleaseSignal);
    lock.lock();
    assertHasWaiters(lock, c, t1, t2);
    c.signalAll();
    assertHasNoWaiters(lock, c);
    lock.unlock();
    awaitTermination(t1);
    awaitTermination(t2);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:26,代码来源:ReentrantLockTest.java

示例3: removeAllChangeListenersThrowExceptionOnNonLooperThread

import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
@Test
public void removeAllChangeListenersThrowExceptionOnNonLooperThread() {
    final CountDownLatch signalTestFinished = new CountDownLatch(1);
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            Realm realm = Realm.getInstance(realmConfig);
            try {
                realm.removeAllChangeListeners();
                fail("Should not be able to invoke removeChangeListener");
            } catch (IllegalStateException ignored) {
            } finally {
                realm.close();
                signalTestFinished.countDown();
            }
        }
    });
    thread.start();

    try {
        TestHelper.awaitOrFail(signalTestFinished);
    } finally {
        thread.interrupt();
    }
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:26,代码来源:RealmTests.java

示例4: waitForChange_runWithRealmThread

import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
@Test
public void waitForChange_runWithRealmThread() throws InterruptedException {
    final CountDownLatch bgRealmStarted = new CountDownLatch(1);
    final CountDownLatch bgRealmFished = new CountDownLatch(1);
    final AtomicBoolean bgRealmChangeResult = new AtomicBoolean(false);
    final AtomicLong bgRealmResultSize = new AtomicLong(0);

    RealmThread thread = new RealmThread(realmConfig, new RealmThread.RealmRunnable() {
        @Override
        public void run(Realm realm) {
            bgRealmStarted.countDown();
            bgRealmChangeResult.set(realm.waitForChange());
            bgRealmResultSize.set(realm.where(AllTypes.class).count());
            realm.close();
            bgRealmFished.countDown();
        }
    });
    thread.start();

    TestHelper.awaitOrFail(bgRealmStarted);
    populateTestRealm();
    TestHelper.awaitOrFail(bgRealmFished);
    assertTrue(bgRealmChangeResult.get());
    assertEquals(TEST_DATA_SIZE, bgRealmResultSize.get());
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:26,代码来源:RealmTests.java

示例5: countDownCallback

import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
private Callback<Object> countDownCallback(final CountDownLatch latch) {
  return new Callback<Object>("countDown") {
    @Override void call(Object listener) {
      latch.countDown();
    }
  };
}
 
开发者ID:paul-hammant,项目名称:googles-monorepo-demo,代码行数:8,代码来源:ListenerCallQueueTest.java

示例6: notifyMonitorToStop

import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
public void notifyMonitorToStop(CountDownLatch stopSignal) {
if ((monitorThread != null) && monitorThread.isAlive()) {
    ((MockMonitor) users[0]).setStopFlag(stopSignal);
} else {
    stopSignal.countDown();
}
   }
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:8,代码来源:MonitorTest.java

示例7: testThenComposeAsync

import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
public void testThenComposeAsync() throws Exception {
    // Composing CompletableFuture is complete
    CompletableFuture<String> cf1 = CompletableFuture.completedFuture("one");

    // Composing function returns a CompletableFuture executed asynchronously
    CountDownLatch cdl = new CountDownLatch(1);
    CompletableFuture<String> cf2 = cf1.thenCompose(str -> CompletableFuture.supplyAsync(() -> {
        while (true) {
            try {
                cdl.await();
                break;
            }
            catch (InterruptedException e) {
            }
        }
        return str + ", two";
    }));

    // Ensure returned CompletableFuture completes after call to thenCompose
    // This guarantees that any premature internal completion will be
    // detected
    cdl.countDown();

    String val = cf2.get();
    Assert.assertNotNull(val);
    Assert.assertEquals(val, "one, two");
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:28,代码来源:ThenComposeAsyncTest.java

示例8: waitForChange_interruptingThread

import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
@Test
public void waitForChange_interruptingThread() throws InterruptedException {
    final CountDownLatch bgRealmOpened = new CountDownLatch(1);
    final CountDownLatch bgRealmClosed = new CountDownLatch(1);
    final AtomicReference<Boolean> bgRealmWaitResult = new AtomicReference<Boolean>();
    final AtomicReference<Realm> bgRealm = new AtomicReference<Realm>();

    // Waits in background.
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            Realm realm = Realm.getInstance(realmConfig);
            bgRealm.set(realm);
            bgRealmOpened.countDown();
            bgRealmWaitResult.set(realm.waitForChange());
            realm.close();
            bgRealmClosed.countDown();
        }
    });
    thread.start();

    TestHelper.awaitOrFail(bgRealmOpened);
    // Makes sure background thread goes to wait.
    Thread.sleep(500);
    // Interrupting a thread should neither cause any side effect nor terminate the Background Realm from waiting.
    thread.interrupt();
    assertTrue(thread.isInterrupted());
    assertEquals(null, bgRealmWaitResult.get());

    // Now we'll stop realm from waiting.
    bgRealm.get().stopWaitForChange();
    TestHelper.awaitOrFail(bgRealmClosed);
    assertFalse(bgRealmWaitResult.get());
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:35,代码来源:RealmTests.java

示例9: multipleInstancesTest

import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
@Test
public void multipleInstancesTest() throws InterruptedException {
    final Set<String> ids = Collections.synchronizedSet(new HashSet<String>());
    final int threadCount = 20;
    final int iterationCount = 10000;
    final CountDownLatch latch = new CountDownLatch(threadCount);

    for (int i = 0; i < threadCount; i++) {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                IDGenerator generator = LocalUniqueIDGeneratorFactory.generatorFor(1, 1);
                try {
                    for (int i = 0; i < iterationCount; i++) {
                        byte[] id = generator.generate();
                        String asHex = Hex.encodeHexString(id);
                        ids.add(asHex);
                    }
                } catch (GeneratorException e) {
                    e.printStackTrace();
                }
                latch.countDown();
            }
        });
        t.start();
    }

    boolean successfullyUnlatched = latch.await(20, TimeUnit.SECONDS);
    assertThat(successfullyUnlatched, is(true));

    assertThat(ids.size(), is(threadCount * iterationCount));
}
 
开发者ID:warlock-china,项目名称:azeroth,代码行数:33,代码来源:UniqueIDGeneratorThreadSafetyIT.java

示例10: testUninterruptible

import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
@Test public void testUninterruptible() throws InterruptedException {
  assumeFalse(threading == Threading.DIRECT);
  assumeTrue(mode == Mode.UNINTERRUPTIBLY);
  maxInFlight = 2;
  List<Integer> numbers = asList(1, 2, 3, 4, 5);
  CountDownLatch allowTranslation = new CountDownLatch(1);
  Thread thread = new Thread(() -> {
    try {
      parallelize(numbers.stream(), input -> {
        try {
          allowTranslation.await();
        } catch (InterruptedException e) {
          thrown.add(e);
          return;
        }
        translateToString(input);
      });
    } catch (InterruptedException | TimeoutException impossible) {
      thrown.add(impossible);
    }
  });
  thread.start();
  thread.interrupt();
  assertThat(translated).isEmpty();
  allowTranslation.countDown();
  thread.join();
  // Even interrupted, all numbers should be printed.
  assertThat(translated).containsExactlyEntriesIn(mapToString(numbers));
}
 
开发者ID:google,项目名称:mug,代码行数:30,代码来源:ParallelizerTest.java

示例11: testDelayedAllocation

import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
/**
 * Test that delayed allocation blocks
 */
@Test
public void testDelayedAllocation() throws Exception {
    BufferPool pool = new BufferPool(5 * 1024, 1024, metrics, time, metricGroup);
    ByteBuffer buffer = pool.allocate(1024, maxBlockTimeMs);
    CountDownLatch doDealloc = asyncDeallocate(pool, buffer);
    CountDownLatch allocation = asyncAllocate(pool, 5 * 1024);
    assertEquals("Allocation shouldn't have happened yet, waiting on memory.", 1L, allocation.getCount());
    doDealloc.countDown(); // return the memory
    assertTrue("Allocation should succeed soon after de-allocation", allocation.await(1, TimeUnit.SECONDS));
}
 
开发者ID:YMCoding,项目名称:kafka-0.11.0.0-src-with-comment,代码行数:14,代码来源:BufferPoolTest.java

示例12: testCloseWaitsForAbort

import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
@Test
public void testCloseWaitsForAbort() throws Exception {
	final CountDownLatch closing = new CountDownLatch(1);
	final CountDownLatch closed = new CountDownLatch(1);
	final AtomicBoolean transactionFinished = new AtomicBoolean(false);
	final AtomicBoolean error = new AtomicBoolean(false);
	final Database<Connection> db = open(false);

	// Start a transaction
	Connection txn = db.startTransaction();
	// In another thread, close the database
	Thread close = new Thread() {
		@Override
		public void run() {
			try {
				closing.countDown();
				db.close();
				if (!transactionFinished.get()) error.set(true);
				closed.countDown();
			} catch (Exception e) {
				error.set(true);
			}
		}
	};
	close.start();
	closing.await();
	// Do whatever the transaction needs to do
	Thread.sleep(10);
	transactionFinished.set(true);
	// Abort the transaction
	db.abortTransaction(txn);
	// The other thread should now terminate
	assertTrue(closed.await(5, SECONDS));
	// Check that the other thread didn't encounter an error
	assertFalse(error.get());
}
 
开发者ID:rafjordao,项目名称:Nird2,代码行数:37,代码来源:H2DatabaseTest.java

示例13: monitorExecutorService

import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
@Test
public void monitorExecutorService() throws InterruptedException {
    CountDownLatch taskStart = new CountDownLatch(1);
    CountDownLatch taskComplete = new CountDownLatch(1);

    ThreadPoolTaskExecutor pool = ThreadPoolTaskExecutorMetrics.monitor(registry, "beep.pool", userTags);
    pool.setMaxPoolSize(1);
    pool.setAwaitTerminationSeconds(1);
    pool.setWaitForTasksToCompleteOnShutdown(true);
    pool.initialize();
    pool.submit(() -> {
        taskStart.countDown();
        taskComplete.await(1, TimeUnit.SECONDS);
        System.out.println("beep");
        return 0;
    });
    pool.submit(() -> System.out.println("boop"));

    taskStart.await(1, TimeUnit.SECONDS);
    assertThat(registry.mustFind("beep.pool.queued").tags(userTags).gauge().value()).isEqualTo(1.0);

    taskComplete.countDown();
    pool.shutdown();

    assertThat(registry.mustFind("beep.pool").tags(userTags).timer().count()).isEqualTo(2L);
    assertThat(registry.mustFind("beep.pool.queued").tags(userTags).gauge().value()).isEqualTo(0.0);
}
 
开发者ID:micrometer-metrics,项目名称:micrometer,代码行数:28,代码来源:ThreadPoolTaskExecutorMetricsTest.java

示例14: testNonResponding

import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
/**
 * Test of nonResponding method, of class SwingWorker.
 */
@Test
public void testNonResponding() throws Exception {
    System.out.println("nonResponding");
    final boolean[] waiting = new boolean[]{false};
    final CountDownLatch latch = new CountDownLatch(1);
    SwingWorker instance = new SwingWorkerImpl(500, true, null, new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
            }
        }
    }, new Runnable() {

        @Override
        public void run() {
            latch.countDown();
        }
    }, null, 
    new Runnable() {

        @Override
        public void run() {
            waiting[0] = true;
        }
    });
    instance.execute();
    latch.await(4, TimeUnit.SECONDS);
    
    assertTrue(waiting[0]);
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:36,代码来源:SwingWorkerTest.java

示例15: testTransformAsync_asyncFunction_cancelledBeforeApplyingFunction

import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
@GwtIncompatible // threads

  public void testTransformAsync_asyncFunction_cancelledBeforeApplyingFunction()
      throws InterruptedException {
    final AtomicBoolean functionCalled = new AtomicBoolean();
    AsyncFunction<String, Integer> function = new AsyncFunction<String, Integer>() {
      @Override
      public ListenableFuture<Integer> apply(String input) throws Exception {
        functionCalled.set(true);
        return immediateFuture(1);
      }
    };
    SettableFuture<String> inputFuture = SettableFuture.create();
    ExecutorService executor = newSingleThreadExecutor();
    ListenableFuture<Integer> future = transformAsync(
        inputFuture, function, executor);

    // Pause the executor.
    final CountDownLatch beforeFunction = new CountDownLatch(1);
    @SuppressWarnings("unused") // go/futurereturn-lsc
    Future<?> possiblyIgnoredError =
        executor.submit(
            new Runnable() {
              @Override
              public void run() {
                awaitUninterruptibly(beforeFunction);
              }
            });

    // Cancel the future after making input available.
    inputFuture.set("value");
    future.cancel(false);

    // Unpause the executor.
    beforeFunction.countDown();
    executor.awaitTermination(5, SECONDS);

    assertFalse(functionCalled.get());
  }
 
开发者ID:zugzug90,项目名称:guava-mock,代码行数:40,代码来源:FuturesTest.java


注:本文中的java.util.concurrent.CountDownLatch.countDown方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。