2012-07-12 35 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

相關問題