How could I use Jython threads since they were Java threads?

For example, I want to play this stream in Jython because I need to run my statemachine from the Java API. I do not own much knowledge in Jython. How can i do this?

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(); 

So, I am trying something like this:

 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: I already tried to do what is commented out in foo.run ()

What am I doing wrong?

+6
source share
1 answer

Well, putting aside the fact that you call the start() method from the run() method, which is very bad, because as soon as the thread is started, if you try to start it again, you will get a thread state exception, otherwise the problem it is most likely that you are using the Jython thread library, not Java.

If you are sure to import as shown below:

 from java.lang import Thread, InterruptedException 

Instead

 from threading import Thread, InterruptedException 

And if you fix the problem mentioned above, most likely your code will work fine.

Using the Jython threading library, you need to modify the code a bit, for example:

 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() 

Which seems to work for me.

+2
source

Source: https://habr.com/ru/post/920369/


All Articles