2011-07-20 70 views
3

我有以下的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”处,并停留在pause()函数上。关于如何继续该计划的任何想法?

回答

2

布赖恩说,多线程和并发是一个巨大的领域,并且更容易弄错了,比它要得到它的权利......

为了让您的代码的工作,你” d需要有这样的事情:

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和由人谁真正知道自己的东西写。我想不出任何会导致这种任意停顿的代码......也许你可以设计你的代码来适应他们的一种使用模式呢?

+1

我正在做的是制作一个游戏的脚本NPC。当玩家与NPC互动时,我会触发继续功能。感谢链接到Gpars;我会研究它。 –

+0

我会看看这一章[在演员](http://www.gpars.org/guide/guide/5.%20Actors.html)。不知道演员如何扩展到游戏可能需要的数千人以上?可能值得在邮件列表上询问(http://xircles.codehaus.org/lists/[email protected])? –

+0

不错的答案tim :) –

2

线程是一个很大的话题,Java中有一些库可以执行许多常见的事情,而无需直接使用Thread API。 “火与忘”的一个简单例子是Timer

但要回答你的直接问题;另一个线程需要通知你的线程继续。参见等待的docs()

导致当前的线程等待,直到其他线程调用 notify()方法或此对象的notifyAll的()方法。在其他 单词中,此方法的行为与其仅执行呼叫 wait(0)完全相同。

一个简单的“修复”就是在您的等待电话中添加一个固定的持续时间,以便继续探索。我会建议这本书'Java Concurrency in Practice'。

synchronized void pause() { 
     //wait 5 seconds before resuming. 
     wait(5000) 
    }