停止线程并等待语句(或方法)被另一个线程执行一定次数的最佳方法是什么? 我在想这样的事情(让“数字”成为一个整数):
number = 5;
while (number > 0) {
synchronized(number) { number.wait(); }
}
...
synchronized(number) {
number--;
number.notify();
}
显然这行不通,首先是因为您似乎不能在 int 类型上使用 wait()。此外,对于这样一个简单的任务,我想到的所有其他解决方案都非常复杂。有什么建议么? (谢谢!)
最佳答案
听起来您正在寻找 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
关于java:等到另一个线程执行一条语句n次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3647436/