2

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

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

...

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

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

4

2 回答 2

6

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

ASemaphore也可以:

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
于 2010-09-05T19:30:46.220 回答
2

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

于 2010-09-05T19:31:09.043 回答