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

标签 java multithreading synchronized

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

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/

相关文章:

java - 为什么 BoneCP 不建立连接?

java - 在 Java 关键部分中,我应该同步什么?

java tomcat a3证书

java - 如何在 JetBrains IntelliJ IDEA 中编辑注释模板并添加类型或函数注释?

c++ - 终止正在运行的 boost 线程

multithreading - 有没有办法采用创建 UI 元素并使其可取消的方法?

c - TFTP 服务器 - 线程版本问题

java - 当使用synchronized来锁定写入时,是否需要使用 volatile 来保护以避免读取旧值或不完整的值?

java - 如何正确退出字节码监视器?

java - jsp 文件中的 JSON 只接受来 self 的 MVC Controller 的 null 返回值。