etu*_*rdu 2 java multithreading synchronized
什么是停止线程并等待另一个线程执行一定次数的语句(或方法)的最佳方法?我正在考虑这样的事情(让"数字"成为一个int):
number = 5;
while (number > 0) {
synchronized(number) { number.wait(); }
}
...
synchronized(number) {
number--;
number.notify();
}
Run Code Online (Sandbox Code Playgroud)
显然这不起作用,首先是因为看起来你不能在int类型上等待().此外,对于我这样一个简单的任务来说,所有其他解决方案对我的Java天真的想法来说都非常复杂.有什么建议?(谢谢!)
听起来像你在寻找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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
326 次 |
| 最近记录: |