我有以下 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() 函数上。关于如何继续该计划的任何想法?
最佳答案
正如 Brian 所说,多线程和并发是一个巨大的领域,做错比做对更容易...
为了让您的代码正常工作,您需要有这样的东西:
abstract class Actor implements Runnable {
synchronized void proceed() { notify() }
synchronized void pause() { wait() }
}
class MyActor extends Actor {
void run() {
println "hi"
pause()
println "hi again"
}
}
def theactor = new MyActor() // Create an instance of MyActor
def actorThread = new Thread( theactor ) // Create a Thread to run this instance in
actorThread.start() // Thread.start() will call MyActor.run()
Thread.sleep( 500 ) // Make the main thread go to sleep for some time so we know the actor class is waiting
theactor.proceed() // Then call proceed on the actor
actorThread.join() // Wait for the thread containing theactor to terminate
但是,如果您使用 Groovy,我会认真考虑使用 a framework like Gpars它为 Groovy 带来了并发性,并且是由真正了解他们的东西的人编写的。然而,我想不出有什么可以允许这种任意代码暂停......也许你可以设计你的代码来适应他们的一种使用模式?
关于Groovy 等待/通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6766010/