# D. Parson CSC 543 Fall 2016. This example code uses Jython # to import and use some Java interfaces & classes to # demonstrate running threads of execution. I am using Jython # so I can interactively demonstrate parts of the Java library. # This is a screen trace from the Sept. 7 class. $ jython >>> from java.lang import * # You need to create an application class to run a new thread. # It subclasses interface java.lang.Runnable, which requires it # to implement the “public void run()” method that is the startup # method for the new thread. Many “active classes” (a class that # runs a service thread for each constructed “active object” # is an “active class”) implement run() as a service loop. >>> class ActiveClass(Runnable): ... def __init__(self): # constructor ... self.value = 1 ... def run(self): ... while(True): ... print self.value ... self.value += 1 ... if self.value > 9: ... return # Returning from run() terminates the thread. ... >>> activeObject = ActiveClass() # Construct an object of our ActiveClass. >>> t = Thread(activeObject) # Construct a java.lang.Thread “around it”. >>> t.start() # Starting the thread creates a thread that invokes run(). >>> 1 2 3 4 5 6 7 8 9 # Below we start 10 concurrent threads. # There is a race condition below in using the output print buffer. >>> for i in range(0,10): ... print "start" ... activeObject = ActiveClass() ... t = Thread(activeObject) ... t.start() ... start start 1 2 start 3 4 5 6 7 1 82 start 19 3 2 4 3 1 start5 6 4 7 2 8 start 593 start 1 1 4 start 22 start 1 6 52 11 23 3 6 start73 4 752 64 4 71 3 84 5 >>> 88 3 45 2 3 94 5 6 9 9 6 65 7 7 8 7 56 96 8 9 87 97 8 8 9 9