代码之家  ›  专栏  ›  技术社区  ›  etuardu

java:等待另一个线程执行一条语句n次

  •  2
  • etuardu  · 技术社区  · 14 年前

    停止线程并等待语句(或方法)被另一个线程执行一定次数的最佳方法是什么? 我在想这样的事情(让“number”是int):

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

    显然,这是行不通的,首先是因为似乎不能在int类型上等待()。此外,对于这样一个简单的任务,我的java天真的头脑中出现的所有其他解决方案都非常复杂。有什么建议吗?(谢谢!)

    2 回复  |  直到 14 年前
        1
  •  6
  •   Jon Skeet    14 年前

    听起来你在找 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
    

    A 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
  •  2
  •   Steven Schlansker    14 年前

    你可能会发现像 CountDownLatch 有用。