本文整理汇总了Java中java.util.concurrent.CountDownLatch.await方法的典型用法代码示例。如果您正苦于以下问题:Java CountDownLatch.await方法的具体用法?Java CountDownLatch.await怎么用?Java CountDownLatch.await使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.concurrent.CountDownLatch
的用法示例。
在下文中一共展示了CountDownLatch.await方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testListener
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
@Test()
public void testListener() throws Exception {
final Path keyfile = Paths.get("./junit/etc/minebox/randomkey.txt");
try {
Assert.assertFalse(Files.exists(keyfile));
final LazyEncyptionKeyProvider key = new LazyEncyptionKeyProvider("./junit/etc/minebox/randomkey.txt");
final ListenableFuture<String> masterPassword = key.getMasterPassword();
Assert.assertFalse(masterPassword.isDone());
final CountDownLatch count = new CountDownLatch(1);
masterPassword.addListener(count::countDown, Executors.newSingleThreadExecutor());
Files.write(keyfile, PWBYTES);
count.await();
Assert.assertTrue(masterPassword.isDone());
Assert.assertEquals(PW, key.getImmediatePassword());
} finally {
Files.delete(keyfile);
}
}
示例2: testPoolThreads10Connections10Validate
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
@Test
public void testPoolThreads10Connections10Validate() throws Exception {
this.datasource.getPoolProperties().setMaxActive(10);
this.datasource.getPoolProperties().setTestOnBorrow(true);
this.datasource.getPoolProperties().setFairQueue(false);
this.threadcount = 10;
this.transferProperties();
this.datasource.getConnection().close();
latch = new CountDownLatch(threadcount);
long start = System.currentTimeMillis();
for (int i=0; i<threadcount; i++) {
TestThread t = new TestThread();
t.setName("tomcat-pool-validate-"+i);
t.d = this.datasource;
t.start();
}
latch.await();
long delta = System.currentTimeMillis() - start;
System.out.println("[testPoolThreads10Connections10Validate]Test complete:"+delta+" ms. Iterations:"+(threadcount*this.iterations));
tearDown();
}
示例3: noCrashIfRunningOnUiThread
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
@Test(timeout = 2000)
public void noCrashIfRunningOnUiThread() throws InterruptedException {
final CountDownLatch countDownLatch = new CountDownLatch(1);
final AtomicReference<Throwable> throwable = new AtomicReference<>();
new Handler(Looper.getMainLooper())
.post(new Runnable() {
@Override
public void run() {
try {
MainActivity.onClickWithWorkerThreadHelper(
getTargetContext().getApplicationContext());
} catch (Exception e) {
throwable.set(e);
} finally {
countDownLatch.countDown();
}
}
});
countDownLatch.await();
assertNull(throwable.get());
}
示例4: getMicroserviceInstance
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
@Override
public List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId) {
Holder<GetInstancesResponse> holder = new Holder<>();
IpPort ipPort = ipPortManager.getAvailableAddress();
CountDownLatch countDownLatch = new CountDownLatch(1);
RestUtils.get(ipPort,
String.format(Const.REGISTRY_API.MICROSERVICE_INSTANCE_OPERATION_ALL, providerId),
new RequestParam().addHeader("X-ConsumerId", consumerId),
syncHandler(countDownLatch, GetInstancesResponse.class, holder));
try {
countDownLatch.await();
if (holder.value != null) {
return holder.value.getInstances();
}
} catch (Exception e) {
LOGGER.error("query microservice instances {} failed", providerId, e);
}
return null;
}
示例5: startTest
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
@Override
protected void startTest() {
log.info(users.length + (users.length == 1 ? " learner begins studying..." : " learners begin studying..."));
allDoneSignal = new CountDownLatch(users.length);
for (int i = 0; i < users.length; i++) {
MockLearner learner = (MockLearner) users[i];
new Thread(learner, learner.getUsername()).start();
}
try {
allDoneSignal.await();
log.info(composeEndInfo());
} catch (InterruptedException e) {
log.debug(e.getMessage(), e);
// what to do?
}
}
示例6: concurrentExec
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
private void concurrentExec(
final Runnable task, final int numThreads) throws Throwable {
startSignal = new CountDownLatch(numThreads);
doneSignal = new CountDownLatch(numThreads);
for (int i = 0; i < numThreads; ++i) {
new Thread(new Runnable() {
@Override
public void run() {
try {
startSignal.countDown();
startSignal.await();
task.run();
} catch (Throwable e) {
failures.incrementAndGet();
e.printStackTrace();
}
doneSignal.countDown();
}
}).start();
}
doneSignal.await();
}
示例7: testPoolThreads10Connections10
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
@Test
public void testPoolThreads10Connections10() throws Exception {
this.datasource.getPoolProperties().setMaxActive(10);
this.datasource.getPoolProperties().setFairQueue(false);
this.threadcount = 10;
this.transferProperties();
this.datasource.getConnection().close();
latch = new CountDownLatch(threadcount);
long start = System.currentTimeMillis();
for (int i=0; i<threadcount; i++) {
TestThread t = new TestThread();
t.setName("tomcat-pool-"+i);
t.d = this.datasource;
t.start();
}
latch.await();
long delta = System.currentTimeMillis() - start;
System.out.println("[testPoolThreads10Connections10]Test complete:"+delta+" ms. Iterations:"+(threadcount*this.iterations));
tearDown();
}
示例8: waitForEvent
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
/**
* Wait for the given CountDownLatch to countdown or to exceed its timeout
* (10000ms if no time specified). The noFail argument stops JUnit.fail
* from being called when the latch is not released.
*/
public static void waitForEvent(CountDownLatch latch, long timeout, Boolean noFail) throws InterruptedException {
//We may get stuck if the consumer finishes processing faster than the test works through
//If so, we need to test for a non-empty status set with last bean status equal to our expectation
//Once finished, check whether the latch was released or timedout
boolean released = latch.await(timeout, TimeUnit.MILLISECONDS);
if (released) {
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~\n Final state reached\n~~~~~~~~~~~~~~~~~~~~~~~~~");
} else {
System.out.println("#########################\n No final state reported\n#########################");
if (!noFail) {
fail("No final state reported");
}
}
}
示例9: testQueuedTasksAreDelegatedInOrderOfSubmission
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
@Test
public void testQueuedTasksAreDelegatedInOrderOfSubmission()
throws Exception {
// Delegate to a single-threaded executor
Executor delegate = Executors.newSingleThreadExecutor();
// Allow two tasks to be delegated at a time
PoliteExecutor polite = new PoliteExecutor(TAG, delegate, 2);
final List<Integer> list = new Vector<Integer>();
final CountDownLatch latch = new CountDownLatch(TASKS);
for (int i = 0; i < TASKS; i++) {
final int result = i;
polite.execute(new Runnable() {
@Override
public void run() {
list.add(result);
latch.countDown();
}
});
}
// Wait for all the tasks to finish
latch.await();
// The tasks should have run in the order they were submitted
assertEquals(ascendingOrder(), list);
}
示例10: main
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
public static void main(String args[]) throws Exception {
countDownLatch = new CountDownLatch(1);
SwingUtilities.invokeLater(WindowsClassicHiDPIIconsTest::createUI);
countDownLatch.await(15, TimeUnit.MINUTES);
if (!testResult) {
throw new RuntimeException("Test fails!");
}
}
示例11: compare
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
/**
* Perform comparisons of the given digests lists. If each list points to
* the same object, only the above-diagonal elements of the comparison
* matrix will be performed
*
* @param hashesA the list of min-hashes for the first set, ordered
* @param filesA the list of file names for the first set, ordered
* @param hashesB the list of min-hashes for the second set, ordered
* @param filesB the list of file names for the first set, ordered
* @throws InterruptedException
*/
public void compare(List<int[]> hashesA, List<String> filesA, List<int[]> hashesB, List<String> filesB) throws InterruptedException
{
CountDownLatch latch = new CountDownLatch(hashesA.size());
for(int i = 0; i < hashesA.size(); i++)
{
int[] hAiH = hashesA.get(i);
String hAiN = filesA.get(i);
int j_start;
if(hashesA == hashesB)
j_start = i+1;//don't self compare / repeat comparisons
else
j_start = 0;
ex.submit(() ->
{
for(int j = j_start; j < hashesB.size(); j++)
{
int sim = (int) Math.round(100*LZJDf.similarity(hAiH, hashesB.get(j)));
if(sim >= threshold)
{
StringBuilder toPrint = localToStdOut.get();
toPrint.append(String.format(hAiN + "|" + filesB.get(j) + "|%03d\n", sim));
tryPrint(toPrint);
}
}
latch.countDown();
});
}
latch.await();
printAllLocalBuffers();
}
示例12: testSubmitTask
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
public void testSubmitTask () throws Exception {
MylynSupport supp = MylynSupport.getInstance();
Collection<NbTask> tasks = supp.getTasks(btr);
assertEquals(1, tasks.size());
NbTask task = tasks.iterator().next();
assertNotNull(task);
// outgoing unsubmitted changes
assertEquals(SynchronizationState.OUTGOING, task.getSynchronizationState());
NbTaskDataModel model = task.getTaskDataModel();
String oldSummary = task.getSummary();
TaskAttribute summaryAttr = model.getLocalTaskData().getRoot().getMappedAttribute(TaskAttribute.SUMMARY);
String newSummary = summaryAttr.getValue();
assertTrue(model.hasOutgoingChanges(summaryAttr));
assertFalse(oldSummary.equals(newSummary));
// unsubmitted tasks should contain the task
assertEquals(1, br.getUnsubmittedIssues().size());
final CountDownLatch l = new CountDownLatch(1);
PropertyChangeListener list = new PropertyChangeListener() {
@Override
public void propertyChange (PropertyChangeEvent evt) {
l.countDown();
}
};
br.addPropertyChangeListener(list);
// submit
task = submitTask(task, model);
l.await();
assertEquals(0, br.getUnsubmittedIssues().size());
br.removePropertyChangeListener(list);
// test
assertFalse(model.isDirty());
assertTrue(model.getChangedAttributes().isEmpty());
assertTrue(model.getChangedOldAttributes().isEmpty());
assertEquals(SynchronizationState.SYNCHRONIZED, task.getSynchronizationState());
assertEquals(newSummary, task.getSummary());
}
示例13: stop
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
public void stop() {
if (this.members.isEmpty()) {
return;
}
if (logger.isInfoEnabled()) {
logger.info("Stopping beans in phase " + this.phase);
}
Collections.sort(this.members, Collections.reverseOrder());
CountDownLatch latch = new CountDownLatch(this.smartMemberCount);
Set<String> countDownBeanNames = Collections.synchronizedSet(new LinkedHashSet<String>());
for (LifecycleGroupMember member : this.members) {
if (this.lifecycleBeans.containsKey(member.name)) {
doStop(this.lifecycleBeans, member.name, latch, countDownBeanNames);
}
else if (member.bean instanceof SmartLifecycle) {
// already removed, must have been a dependent
latch.countDown();
}
}
try {
latch.await(this.timeout, TimeUnit.MILLISECONDS);
if (latch.getCount() > 0 && !countDownBeanNames.isEmpty() && logger.isWarnEnabled()) {
logger.warn("Failed to shut down " + countDownBeanNames.size() + " bean" +
(countDownBeanNames.size() > 1 ? "s" : "") + " with phase value " +
this.phase + " within timeout of " + this.timeout + ": " + countDownBeanNames);
}
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
示例14: assertCanPut
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
public void assertCanPut(BlockingQueue<Schedulable> cq, int numberOfPuts,
int putAttempts) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(numberOfPuts);
Putter putter = new Putter(cq, putAttempts, null, latch);
Thread t = new Thread(putter);
t.start();
latch.await();
assertEquals(numberOfPuts, putter.callsAdded);
t.interrupt();
}
示例15: computeProfiles
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
private void computeProfiles( List<MegaFacade> mfs ) {
BlockingQueue<MegaFacade> togo = new ArrayBlockingQueue<>( mfs.size() ); // todo: replace with PArallel
togo.addAll( mfs );
int tCount = Runtime.getRuntime().availableProcessors();
CountDownLatch cdl = new CountDownLatch( tCount );
for (int i = 0; i < tCount; i ++ ) {
new Thread() {
@Override
public void run() {
try {
while (true) {
MegaFacade mf = togo.poll();
System.out.println("megafacades remaining: "+togo.size());
if (mf == null)
return;
mf.computeProfiles( ProfileGen.this );
}
}
finally {
cdl.countDown();
}
}
}.start();
}
try {
cdl.await();
System.out.println("megafacades found");
} catch ( InterruptedException e ) {
e.printStackTrace();
}
}