java:等待另一个线程执行一条语句n次
停止线程并等待另一个线程执行语句(或方法)一定次数的最佳方法是什么? 我正在考虑这样的事情(让“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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听起来您正在寻找
CountDownLatch
。信号量
< /a> 也可以工作:Sounds like you're looking for
CountDownLatch
.A
Semaphore
would also work:您可能会发现类似 CountDownLatch< /a> 有用。
You might find something like a CountDownLatch useful.