【问题标题】:How could I use Jython threads as they were Java threads?我如何使用 Jython 线程,因为它们是 Java 线程?
【发布时间】:2012-07-12 20:41:39
【问题描述】:

例如,我想在 Jython 中重现此线程,因为我需要从 Java API 启动我的 状态机。我对 Jython 的了解不多。我怎样才能做到这一点?

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() 下的注释

我做错了什么?

【问题讨论】:

    标签: java multithreading jython


    【解决方案1】:

    好吧,撇开您从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()
    

    这似乎对我有用。

    【讨论】:

    • 非常感谢,我认为我的问题不在于线程,而在于我的状态机。非常感谢您的关注!
    猜你喜欢
    • 2014-07-04
    • 2015-05-16
    • 1970-01-01
    • 2012-05-21
    • 2015-09-15
    • 2020-06-07
    • 2010-12-19
    • 2012-05-24
    • 2011-01-15
    相关资源
    最近更新 更多