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


Java CountDownLatch.await方法代码示例

本文整理汇总了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);
    }
}
 
开发者ID:MineboxOS,项目名称:minebox,代码行数:19,代码来源:EncyptionKeyProviderTest.java

示例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();
}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:22,代码来源:CheckOutThreadTest.java

示例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());
}
 
开发者ID:jaggernod,项目名称:threatasserter,代码行数:23,代码来源:JavaTest.java

示例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;
}
 
开发者ID:apache,项目名称:incubator-servicecomb-java-chassis,代码行数:21,代码来源:ServiceRegistryClientImpl.java

示例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?
}
   }
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:17,代码来源:LearnerTest.java

示例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();
}
 
开发者ID:fengchen8086,项目名称:ditb,代码行数:23,代码来源:TestRowProcessorEndpoint.java

示例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();
}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:21,代码来源:CheckOutThreadTest.java

示例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");
		}
	}
}
 
开发者ID:eclipse,项目名称:scanning,代码行数:21,代码来源:RealQueueTestUtils.java

示例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);
}
 
开发者ID:rafjordao,项目名称:Nird2,代码行数:25,代码来源:PoliteExecutorTest.java

示例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!");
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:11,代码来源:WindowsClassicHiDPIIconsTest.java

示例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();
}
 
开发者ID:EdwardRaff,项目名称:jLZJD,代码行数:45,代码来源:Main.java

示例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());
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:41,代码来源:MylynStorageTest.java

示例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();
	}
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:32,代码来源:DefaultLifecycleProcessor.java

示例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();
}
 
开发者ID:naver,项目名称:hadoop,代码行数:13,代码来源:TestFairCallQueue.java

示例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();
	}
}
 
开发者ID:twak,项目名称:chordatlas,代码行数:42,代码来源:ProfileGen.java


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