Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

For example I want to reproduce this Thread in Jython because I need to start my statemachine from a Java API.I dont own much knowledge in Jython. How can I do that?

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'm 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 under the foo.run()

What am I doing wrong?

like image 493
hudsonsferreira Avatar asked Jul 12 '12 20:07

hudsonsferreira


1 Answers

Well, putting aside the fact that you are calling the start() method from within the run() method, which is a really bad idea because once a thread is started, if you attempt to start it again you will get a thread state exception, setting that aside, the problem is, most probably, that you are using Jython threading library and not Java's.

If you make sure to import as follows:

from java.lang import Thread, InterruptedException

Instead of

from threading import Thread, InterruptedException

And if you correct the problem I cited above, chances are that your code will run just fine.

Using the Jython's threading library, you would need to change the code a bit, somewhat like:

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 appears to work for me.

like image 109
Edwin Dalorzo Avatar answered Oct 22 '22 18:10

Edwin Dalorzo