Groovy 等待/通知
我有以下 Groovy 代码:
abstract class Actor extends Script {
synchronized void proceed() {
this.notify()
}
synchronized void pause() {
wait()
}
}
class MyActor extends Actor {
def run() {
println "hi"
pause()
println "hi again"
}
}
def theactor = new MyActor()
theactor.run()
theactor.proceed()
当我运行代码时,我希望代码输出“hi”和“hi Again”。相反,它只是停在“hi”处并卡在pause()函数上。关于如何继续该计划有什么想法吗?
I have the following Groovy code:
abstract class Actor extends Script {
synchronized void proceed() {
this.notify()
}
synchronized void pause() {
wait()
}
}
class MyActor extends Actor {
def run() {
println "hi"
pause()
println "hi again"
}
}
def theactor = new MyActor()
theactor.run()
theactor.proceed()
When I run the code, I want the code to output "hi" and "hi again". Instead, it just stops at "hi" and gets stuck on the pause() function. Any idea on how I could continue the program?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如布莱恩所说,多线程和并发是一个巨大的领域,出错比正确更容易......
为了让你的代码正常工作,你需要有这样的东西:
但是,如果如果你正在使用 Groovy,我会认真考虑使用 像 Gpars 这样的框架,它为 Groovy 带来了并发性,并且是由人们编写的谁真正了解他们的东西。然而,我想不出任何允许这种任意暂停代码的东西......也许你可以设计你的代码来适应他们的使用模式之一?
As Brian says, multithreading and concurrency is a huge area, and it is easier to get it wrong, than it is to get it right...
To get your code working, you'd need to have something like this:
However, if you are using Groovy, I would seriously consider using a framework like Gpars which brings concurrency to Groovy and is written by people who really know their stuff. I can't think of anything that llows this sort of arbitrary pausing of code however... Maybe you could design your code to fit one of their usage patterns instead?
线程是一个很大的话题,Java 中有一些库可以完成许多常见的事情,而无需直接使用 Thread API。 “Fire and Forget”的一个简单示例是 Timer 。
但要回答你眼前的问题;另一个线程需要通知您的线程继续。请参阅文档 等待()
一个简单的“修复”就是为您的等待调用添加固定的持续时间,以便继续您的探索。我推荐这本书“Java 并发实践”。
Threading is a big topic and there are libraries in Java to do many common things without working with the Thread API directly. One simple example for 'Fire and Forget' is Timer.
But to answer your immediate question; another thread needs to notify your thread to continue. See the docs on wait()
One simple 'fix' is to just add a fixed duration to your wait call just to continue with your exploration. I would suggest the book 'Java Concurrency in Practice'.