當前位置: 首頁>>代碼示例>>Java>>正文


Java CountDownLatch.getCount方法代碼示例

本文整理匯總了Java中java.util.concurrent.CountDownLatch.getCount方法的典型用法代碼示例。如果您正苦於以下問題:Java CountDownLatch.getCount方法的具體用法?Java CountDownLatch.getCount怎麽用?Java CountDownLatch.getCount使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.util.concurrent.CountDownLatch的用法示例。


在下文中一共展示了CountDownLatch.getCount方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: testDoRetry_subscribe

import java.util.concurrent.CountDownLatch; //導入方法依賴的package包/類
@Test
public void testDoRetry_subscribe() throws Exception {

    final CountDownLatch latch = new CountDownLatch(1);//全部共調用4次。成功才會減1. subscribe的失敗嘗試不會在做了

    registry = new MockRegistry(registryUrl, latch);
    registry.setBad(true);
    registry.register(serviceUrl);

    registry.setBad(false);

    for (int i = 0; i < trytimes; i++) {
        System.out.println("failback registry retry ,times:" + i);
        if (latch.getCount() == 0)
            break;
        Thread.sleep(sleeptime);
    }
    assertEquals(0, latch.getCount());
}
 
開發者ID:l1325169021,項目名稱:github-test,代碼行數:20,代碼來源:FailbackRegistryTest.java

示例2: preGetOp

import java.util.concurrent.CountDownLatch; //導入方法依賴的package包/類
@Override
public void preGetOp(final ObserverContext<RegionCoprocessorEnvironment> e,
                     final Get get, final List<Cell> results) throws IOException {

  if (e.getEnvironment().getRegion().getRegionInfo().getReplicaId() == 0) {
    CountDownLatch latch = cdl.get();
    try {
      if (sleepTime.get() > 0) {
        LOG.info("Sleeping for " + sleepTime.get() + " ms");
        Thread.sleep(sleepTime.get());
      } else if (latch.getCount() > 0) {
        LOG.info("Waiting for the counterCountDownLatch");
        latch.await(2, TimeUnit.MINUTES); // To help the tests to finish.
        if (latch.getCount() > 0) {
          throw new RuntimeException("Can't wait more");
        }
      }
    } catch (InterruptedException e1) {
      LOG.error(e1);
    }
  } else {
    LOG.info("We're not the primary replicas.");
  }
}
 
開發者ID:fengchen8086,項目名稱:ditb,代碼行數:25,代碼來源:TestReplicaWithCluster.java

示例3: test1

import java.util.concurrent.CountDownLatch; //導入方法依賴的package包/類
@Test
public void test1() throws InterruptedException {

    setupPeers();

    // A == b10, B == genesis

    final CountDownLatch semaphore = new CountDownLatch(1);
    ethereumB.addListener(new EthereumListenerAdapter() {
        @Override
        public void onBlock(Block block, List<TransactionReceipt> receipts) {
            if (block.isEqual(b10)) {
                semaphore.countDown();
            }
        }
    });

    semaphore.await(40, SECONDS);

    // check if B == b10
    if(semaphore.getCount() > 0) {
        fail("PeerB bestBlock is incorrect");
    }
}
 
開發者ID:Aptoide,項目名稱:AppCoins-ethereumj,代碼行數:25,代碼來源:LongSyncTest.java

示例4: triggerAndWaitForThreads

import java.util.concurrent.CountDownLatch; //導入方法依賴的package包/類
private long triggerAndWaitForThreads(List<PosterThread> threads, CountDownLatch latch) throws InterruptedException {
    while (latch.getCount() != 1) {
        // Let all other threads prepare and ensure this one is the last 
        Thread.sleep(1);
    }
    long start = System.currentTimeMillis();
    latch.countDown();
    for (PosterThread thread : threads) {
        thread.join();
    }
    return System.currentTimeMillis() - start;
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:13,代碼來源:EventBusMultithreadedTest.java

示例5: main

import java.util.concurrent.CountDownLatch; //導入方法依賴的package包/類
public static void main(String[] args) throws Throwable {
    final String[] algorithmNames = {
        "PBKDF2WITHHMACSHA1",
        "PBEWITHMD5ANDDES",
        "DSA",
        "SHA384WITHRSA",
        "RSA",
        "SHA1WITHDSA",
        "SHA512WITHRSA",
        "MD2WITHRSA",
        "PBEWITHSHA1ANDDESEDE",
        "SHA1WITHRSA",
        "DIFFIEHELLMAN",
        "MD5WITHRSA",
        "PBEWITHSHA1ANDRC2_40",
        "SHA256WITHRSA",
    };

    final int THREADS = 2;
    final ExecutorService pool = Executors.newFixedThreadPool(THREADS);
    final CountDownLatch startingGate = new CountDownLatch(THREADS);
    final Runnable r = new Runnable() { public void run() {
        startingGate.countDown();
        do {} while (startingGate.getCount() > 0);
        try {
            for (String algorithmName : algorithmNames)
                AlgorithmId.get(algorithmName);
        } catch (Throwable fail) {
            throw new AssertionError(fail);
        }
    }};
    final ArrayList<Future<?>> futures = new ArrayList<>();
    for (int i = 0; i < THREADS; i++)
        futures.add(pool.submit(r));
    pool.shutdown();
    for (Future<?> future : futures) future.get();
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:38,代碼來源:OidTableInit.java

示例6: run

import java.util.concurrent.CountDownLatch; //導入方法依賴的package包/類
@Override
public void run()
{
	try {
		while ( !handler.allFinished() )
		{
			if (failure) throw new RuntimeException("FAILURE DETECTED!");
			List<Thread> thrds = new LinkedList<Thread>();
			for ( TeamedAgentId id : localWorldViews.keySet() )
			{
				if ( handler.cyclesToRun(id) >= 0)
				{
					thrds.add( new EventGenerator(eventsPerCycle, currentTime, localWorldViews.get(id), checkers.get(id) ) );
				}
			}
			latch2 = new CountDownLatch(thrds.size());
			for (Thread t : thrds)
			{
				t.start();
			}
			latch2.await(GLOBAL_TIMEOUT_IN_MINUTES, TimeUnit.MINUTES);					
			if (latch2.getCount() > 0 || failure) {
				throw new RuntimeException("FAILURE DETECTED!");
			}
			++currentTime;
			sleep(sleepTime);					
		}
	} catch (Exception e) {
		e.printStackTrace();
		failure = true;
		totalCountDown();	
		return;
	}
	latch.countDown();
}
 
開發者ID:kefik,項目名稱:Pogamut3,代碼行數:36,代碼來源:Test02_UT2004VisionLocalWorldView_visibilityTest.java

示例7: 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

示例8: testDoRetry

import java.util.concurrent.CountDownLatch; //導入方法依賴的package包/類
/**
     * Test method for
     * {@link com.alibaba.dubbo.registry.internal.FailbackRegistry#doRetry()}.
     *
     * @throws Exception
     */
    @Test
    public void testDoRetry() throws Exception {

        final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false);
        final CountDownLatch latch = new CountDownLatch(3);//全部共調用3次。成功才會減1. subscribe register的失敗嘗試不會在做了

        NotifyListener listner = new NotifyListener() {
            public void notify(List<URL> urls) {
                notified.set(Boolean.TRUE);
            }
        };
        registry = new MockRegistry(registryUrl, latch);
        registry.setBad(true);
        registry.register(serviceUrl);
        registry.unregister(serviceUrl);
        registry.subscribe(serviceUrl.setProtocol(Constants.CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")), listner);
        registry.unsubscribe(serviceUrl.setProtocol(Constants.CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")), listner);

        //失敗的情況不能調用到listener.
        assertEquals(false, notified.get());
        assertEquals(3, latch.getCount());

        registry.setBad(false);

        for (int i = 0; i < trytimes; i++) {
            System.out.println("failback registry retry ,times:" + i);
            //System.out.println(latch.getCount());
            if (latch.getCount() == 0)
                break;
            Thread.sleep(sleeptime);
        }
//        Thread.sleep(100000);//for debug
        assertEquals(0, latch.getCount());
        //unsubscribe時會清除failedsubcribe對應key
        assertEquals(false, notified.get());
    }
 
開發者ID:l1325169021,項目名稱:github-test,代碼行數:43,代碼來源:FailbackRegistryTest.java

示例9: test2

import java.util.concurrent.CountDownLatch; //導入方法依賴的package包/類
@Test
public void test2() throws InterruptedException {

    SysPropConfigA.eth62 = new Eth62() {

        @Override
        protected void processGetBlockBodies(GetBlockBodiesMessage msg) {
            List<byte[]> bodies = Arrays.asList(
                    mainB1B10.get(0).getEncodedBody()
            );

            BlockBodiesMessage response = new BlockBodiesMessage(bodies);
            sendMessage(response);
        }
    };

    setupPeers();

    // A == b10, B == genesis

    final CountDownLatch semaphoreDisconnect = new CountDownLatch(1);
    ethereumA.addListener(new EthereumListenerAdapter() {
        @Override
        public void onRecvMessage(Channel channel, Message message) {
            if (message instanceof DisconnectMessage) {
                semaphoreDisconnect.countDown();
            }
        }
    });

    semaphoreDisconnect.await(10, SECONDS);

    // check if peer was dropped
    if(semaphoreDisconnect.getCount() > 0) {
        fail("PeerA is not dropped");
    }
}
 
開發者ID:talentchain,項目名稱:talchain,代碼行數:38,代碼來源:LongSyncTest.java

示例10: testDoRetry_register

import java.util.concurrent.CountDownLatch; //導入方法依賴的package包/類
@Test
    public void testDoRetry_register() throws Exception {

        final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false);
        final CountDownLatch latch = new CountDownLatch(1);//全部共調用4次。成功才會減1. subscribe的失敗嘗試不會在做了

        NotifyListener listner = new NotifyListener() {
            public void notify(List<URL> urls) {
                notified.set(Boolean.TRUE);
            }
        };
        registry = new MockRegistry(registryUrl, latch);
        registry.setBad(true);
        registry.subscribe(serviceUrl.setProtocol(Constants.CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")), listner);

        //失敗的情況不能調用到listener.
        assertEquals(false, notified.get());
        assertEquals(1, latch.getCount());

        registry.setBad(false);

        for (int i = 0; i < trytimes; i++) {
            System.out.println("failback registry retry ,times:" + i);
            //System.out.println(latch.getCount());
            if (latch.getCount() == 0)
                break;
            Thread.sleep(sleeptime);
        }
//        Thread.sleep(100000);
        assertEquals(0, latch.getCount());
        //unsubscribe時會清除failedsubcribe對應key
        assertEquals(true, notified.get());
    }
 
開發者ID:flychao88,項目名稱:dubbocloud,代碼行數:34,代碼來源:FailbackRegistryTest.java

示例11: executeThenAdd_singleThreaded

import java.util.concurrent.CountDownLatch; //導入方法依賴的package包/類
@Benchmark int executeThenAdd_singleThreaded(int reps) {
  int returnValue = 0;
  for (int i = 0; i < reps; i++) {
    list = impl.newExecutionList();
    list.execute();
    listenerLatch = new CountDownLatch(numListeners);
    for (int j = 0; j < numListeners; j++) {
      list.add(listener, directExecutor());
      returnValue += listenerLatch.getCount();
    }
    returnValue += listenerLatch.getCount();
  }
  return returnValue;
}
 
開發者ID:zugzug90,項目名稱:guava-mock,代碼行數:15,代碼來源:ExecutionListBenchmark.java

示例12: testDoRetry

import java.util.concurrent.CountDownLatch; //導入方法依賴的package包/類
/**
     * Test method for
     * {@link com.alibaba.dubbo.registry.internal.FailbackRegistry#doRetry()}.
     * 
     * @throws Exception
     */
    @Test
    public void testDoRetry() throws Exception {

        final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false);
        final CountDownLatch latch = new CountDownLatch(3);//全部共調用3次。成功才會減1. subscribe register的失敗嘗試不會在做了

        NotifyListener listner = new NotifyListener() {
            public void notify(List<URL> urls) {
                notified.set(Boolean.TRUE);
            }
        };
        registry = new MockRegistry(registryUrl, latch);
        registry.setBad(true);
        registry.register(serviceUrl);
        registry.unregister(serviceUrl);
        registry.subscribe(serviceUrl.setProtocol(Constants.CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")), listner);
        registry.unsubscribe(serviceUrl.setProtocol(Constants.CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")), listner);

        //失敗的情況不能調用到listener.
        assertEquals(false, notified.get());
        assertEquals(3, latch.getCount());

        registry.setBad(false);

        for (int i = 0; i < trytimes; i++) {
            System.out.println("failback registry retry ,times:" + i);
            //System.out.println(latch.getCount());
            if (latch.getCount() == 0)
                break;
            Thread.sleep(sleeptime);
        }
//        Thread.sleep(100000);//for debug
        assertEquals(0, latch.getCount());
        //unsubscribe時會清除failedsubcribe對應key
        assertEquals(false, notified.get());
    }
 
開發者ID:flychao88,項目名稱:dubbocloud,代碼行數:43,代碼來源:FailbackRegistryTest.java

示例13: test2

import java.util.concurrent.CountDownLatch; //導入方法依賴的package包/類
@Test
public void test2() throws InterruptedException {

    setupPeers();

    // A == B == genesis

    Blockchain blockchainA = (Blockchain) ethereumA.getBlockchain();

    for (Block b : forkB1B5B8_) {
        blockchainA.tryToConnect(b);
    }

    // A == b8', B == genesis

    final CountDownLatch semaphore = new CountDownLatch(1);
    ethereumB.addListener(new EthereumListenerAdapter() {
        @Override
        public void onBlock(Block block, List<TransactionReceipt> receipts) {
            if (block.isEqual(b8_)) {
                semaphore.countDown();
            }
        }
    });

    ethA.sendNewBlock(b8_);

    semaphore.await(10, SECONDS);

    // check if B == b8'
    if(semaphore.getCount() > 0) {
        fail("PeerB bestBlock is incorrect");
    }
}
 
開發者ID:talentchain,項目名稱:talchain,代碼行數:35,代碼來源:ShortSyncTest.java

示例14: initCluster

import java.util.concurrent.CountDownLatch; //導入方法依賴的package包/類
protected void initCluster() {
    long instanceId = EstTime.currentTimeMillis();
    hstore_site.setInstanceId(instanceId);
    InitializeRequest request = InitializeRequest.newBuilder()
                                        .setSenderSite(0)
                                        .setInstanceId(instanceId)
                                        .build();
    final CountDownLatch latch = new CountDownLatch(this.num_sites-1); 
    RpcCallback<InitializeResponse> callback = new RpcCallback<InitializeResponse>() {
        @Override
        public void run(InitializeResponse parameter) {
            if (debug.val) LOG.debug(String.format("Initialization Response: %s / %s",
                                   HStoreThreadManager.formatSiteName(parameter.getSenderSite()),
                                   parameter.getStatus()));
            latch.countDown();
        }
    };
    for (int site_id = 0; site_id < this.num_sites; site_id++) {
        if (site_id == this.local_site_id) continue;
        ProtoRpcController controller = new ProtoRpcController();
        this.channels[site_id].initialize(controller, request, callback);
    } // FOR
    
    if (latch.getCount() > 0) {
        if (debug.val)
            LOG.debug(String.format("Waiting for %s initialization responses", latch.getCount()));
        boolean finished = false;
        try {
            finished = latch.await(10, TimeUnit.SECONDS);
        } catch (InterruptedException ex) {
            throw new ServerFaultException("Unexpected interruption", ex);
        }
        assert(finished);
    }
}
 
開發者ID:s-store,項目名稱:s-store,代碼行數:36,代碼來源:HStoreCoordinator.java

示例15: testPdfToTextConversions

import java.util.concurrent.CountDownLatch; //導入方法依賴的package包/類
/**
 * Added to test a single transform that appeared to have problems.
 * Commented out once issue was fixed, but left in the code to help with
 * future issues.
 * @throws Exception
 */
public void testPdfToTextConversions() throws Exception
{
    final String sourceMimetype = MimetypeMap.MIMETYPE_PDF;
    final String targetMimetype = MimetypeMap.MIMETYPE_TEXT_PLAIN;
    int transforms = 100;
    final String filename = "svn-book.pdf";
    
    final CountDownLatch doneSignal = new CountDownLatch(transforms);
    
    int threadCount = 8;
    final ExecutorService threadPool = Executors.newFixedThreadPool(threadCount);
    long time = System.currentTimeMillis();
    for (int i=0; i<transforms; i++)
        
    {
        threadPool.submit(new Runnable() {
            public void run()
            {
                try
                {
                    pdfToTextTransform(filename, sourceMimetype, targetMimetype);
                    doneSignal.countDown();
                }
                catch (IOException e)
                {
                    threadPool.shutdown();
                    e.printStackTrace();
                }
            }});
        if (i < threadCount)
        {
            Thread.sleep(1000);
        }
    }
    boolean okay = doneSignal.await(100, TimeUnit.SECONDS);
    
    time = System.currentTimeMillis() - time;
    transforms = transforms - (int)doneSignal.getCount();
    String message = "Total time "+time+" ms   "+(transforms > 0 ? "average="+(time/transforms)+" ms" : "")+"  threads="+threadCount+"  transforms="+transforms;
    System.out.println(message);
    
    if (!okay)
    {
        // Before the changes to PDFBox, this would fail having only done about 50 transforms.
        // After the change, this takes about 55 seconds
        fail("********** Transforms did not finish ********** "+message);
    }
}
 
開發者ID:Alfresco,項目名稱:alfresco-repository,代碼行數:55,代碼來源:PdfBoxContentTransformerTest.java


注:本文中的java.util.concurrent.CountDownLatch.getCount方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。