Groovy 等待/通知

标签 groovy wait synchronized notify

我有以下 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/

相关文章:

java - 同步与 ReadWriteLock 性能

gradle - 如何将模块中的排除项聚合到根排除项中?

java - 如何使用数据库存储的 GString 定义生成运行时数据

python - python中的异步等待/非阻塞等待

java - 将 synchronized() 与 ReentrantLock.lock() 混合使用

java - 可运行对象中的此方法是否需要同步?

groovy - 用户定义的变量显示为 48 而不是 0

grails - Grails 2.2.2 createCriteria抛出错误

java - sleep 暂停整个线程

android - 等待和引擎的功能?