From: Kevin B. <kb...@ca...> - 2002-03-01 15:46:54
|
Stephen Naicken wrote: > > I'm not sure as to how to go about threading a jython program. I am > trying to use from java.lang import Thread, extending the Thread class > and overriding thr run method. However, when I do this in jython, I get > an error telling me the __call__ attribute has not been set. As a design principle, it is often better to implement Runnable rather than extending Thread (you have Runnable jobs to do, rather than anything that would change the semantics of a Thread). > If anyone can provide a small example of how to create a threaded app in > jython I would be very grateful. Four small examples (Jython tends to violate Python's "one obvious way to do it" principle), ordered as Python over Java, then preferred over less preferred: def greet( name ): print "greetings", name count = 0 # newer Python way import threading count += 1 t = threading.Thread( target=greet, name="MyThread %d" % count, args=( "threading.Thread", ) ) t.start() # older Python way # has no thread naming feature import thread thread.start_new_thread( greet, ( "thread.start_new_thread", ) ) # preferred Java way from java.lang import Thread, Runnable class GreetJob( Runnable ): def __init__( self, name ): self.name = name def run( self ): greet( self.name ) count += 1 t = Thread( GreetJob( "Runnable" ), "MyThread %d" % count ) t.start() # other Java way from java.lang import Thread class GreetThread( Thread ): def __init__( self, name, count ): Thread.__init__( self, "MyThread %d" % count ) self._name = name # Thread has a 'name' attribute def run( self ): greet( self._name ) count += 1 t = GreetThread( "Thread subclass", count ) t.start() *whew* BTW, the thread naming stuff is good practice but not required. kb |