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

发布于 2024-09-17 11:39:41 字数 333 浏览 5 评论 0原文

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

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

...

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

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

what is the best way to stop a thread and wait for a statement (or a method) to be executed a certain number of times by another thread?
I was thinking about something like this (let "number" be an int):

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

...

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

Obviously this wouldn't work, first of all because it seems you can't wait() on a int type. Furthermore, all other solutions that come to my java-naive mind are really complicated for such a simple task. Any suggestions? (Thanks!)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蓝海 2024-09-24 11:39:41

听起来您正在寻找 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 = new Semaphore(0);
...
semaphore.acquire(5);

// Other thread... in a loop
semaphore.release(); // When this has executed 5 times, first thread will unblock

Sounds like you're looking for 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 would also work:

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
枉心 2024-09-24 11:39:41

您可能会发现类似 CountDownLatch< /a> 有用。

You might find something like a CountDownLatch useful.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文