【问题标题】:java: wait until another thread performs a statement n timesjava:等到另一个线程执行一条语句n次
【发布时间】:2010-09-05 19:29:07
【问题描述】:

停止线程并等待另一个线程执行一定次数的语句(或方法)的最佳方法是什么? 我正在考虑这样的事情(让“数字”成为一个整数):

number = 5;
while (number > 0) {
   synchronized(number) { number.wait(); }
}

...

synchronized(number) {
   number--;
   number.notify();
}

显然这行不通,首先是因为您似乎不能在 int 类型上使用 wait()。此外,对于这样一个简单的任务,我想到的所有其他解决方案都非常复杂。有什么建议么? (谢谢!)

【问题讨论】:

    标签: java multithreading synchronized


    【解决方案1】:

    听起来你在寻找CountDownLatch

    CountDownLatch latch = new CountDownLatch(5);
    ...
    latch.await(); // Possibly put timeout
    
    
    // Other thread... in a loop
    latch.countDown(); // When this has executed 5 times, first thread will unblock
    

    Semaphore 也可以:

    Semaphore semaphore = new Semaphore(0);
    ...
    semaphore.acquire(5);
    
    // Other thread... in a loop
    semaphore.release(); // When this has executed 5 times, first thread will unblock
    

    【讨论】:

      【解决方案2】:

      您可能会发现 CountDownLatch 之类的东西很有用。

      【讨论】:

        猜你喜欢
        • 2021-06-21
        • 1970-01-01
        • 2015-02-22
        • 2012-06-09
        • 1970-01-01
        • 1970-01-01
        • 2023-02-09
        • 2011-08-03
        • 2014-05-23
        相关资源
        最近更新 更多