2012-07-12 34 views
6

例如我想在Jython中重现此线程,因为我需要从Java API开始我的状态机。我没有在Jython中拥有太多知识。我怎样才能做到这一点?我如何使用Jython线程,因为它们是Java线程?

Thread thread = new Thread() { 
    @Override 
    public void run() { 
     statemachine.enter(); 
     while (!isInterrupted()) { 
      statemachine.getInterfaceNew64().getVarMessage(); 
      statemachine.runCycle(); 
      try { 
       Thread.sleep(100); 
      } catch (InterruptedException e) { 
       interrupt(); 
      } 
     }    
    } 
}; 
thread.start(); 

所以我想是这样的:

class Cycle(Thread, widgets.Listener): 
    def run(self): 
     self.statemachine = New64CycleBasedStatemachine() 
     self.statemachine.enter() 
     while not self.currentThread().isInterrupted(): 
      self.statemachine.getInterfaceNew64().getVarMessage() 
      self.statemachine.runCycle() 
      try: 
       self.currentThread().sleep(100) 
      except InterruptedException: 
       self.interrupt() 
     self.start() 

foo = Cycle() 
foo.run() 
#foo.start() 

PS:我已经尝试过做什么foo.run()

我在做什么错在评论?

回答

2

好吧,抛开您呼叫从run()方法,这是一个非常糟糕的主意内start()方法,因为一旦一个线程启动,如果您尝试再次启动它,你会得到一个线程状态异常的事实,除此之外,问题很可能在于,您使用的是Jython线程库而不是Java。

如果你一定要导入如下:

from java.lang import Thread, InterruptedException 

而不是

from threading import Thread, InterruptedException 

如果你纠正我上面提到的问题,有可能你的代码将运行得很好。

使用Jython的threading库,你需要改变一下代码,有点像:

from threading import Thread, InterruptedException 
import time 

class Cycle(Thread): 
    canceled = False 

    def run(self): 
     while not self.canceled: 
      try: 
       print "Hello World" 
       time.sleep(1) 
      except InterruptedException: 
       canceled = True 

if __name__ == '__main__': 
    foo = Cycle() 
    foo.start() 

这似乎为我工作。

+0

非常感谢您,我认为我的问题与线程无关,只与我的状态机有关。非常感谢您的关注! – hudsonsferreira 2012-07-15 23:10:41

相关问题