Thread Based Parallelism - Thread in a Subclass
1 import threading 2 import time 3 4 exit_Flag = 0 5 6 class myThread (threading.Thread): 7 def __init__(self, threadID, name, counter): 8 threading.Thread.__init__(self) 9 self.threadID = threadID10 self.name = name11 self.counter = counter12 def run(self):13 print ("Starting " + self.name + "\n")14 print_time(self.name, self.counter, 5)15 print ("Exiting " + self.name + "\n")16 17 def print_time(threadName, delay, counter):18 while counter:19 if exit_Flag:20 thread.exit()21 time.sleep(delay)22 print ("%s: %s" % (threadName, time.ctime(time.time())))23 counter -= 124 25 if __name__ == '__main__':26 # Create two threads27 thread1 = myThread(1, "Thread-1", 1)28 thread2 = myThread(2, "Thread-2", 2)29 30 # Start the Threads created31 thread1.start()32 thread2.start()33 34 # Wait for all thread to complete35 thread1.join()36 thread2.join()37 38 print ("Exiting Main Thread")39 40 Output,41 Starting Thread-142 Starting Thread-243 44 Thread-1: Thu Feb 8 15:08:47 201845 Thread-1: Thu Feb 8 15:08:48 201846 Thread-2: Thu Feb 8 15:08:48 201847 Thread-1: Thu Feb 8 15:08:49 201848 Thread-2: Thu Feb 8 15:08:50 201849 Thread-1: Thu Feb 8 15:08:50 201850 Thread-1: Thu Feb 8 15:08:51 201851 Exiting Thread-152 53 Thread-2: Thu Feb 8 15:08:52 201854 Thread-2: Thu Feb 8 15:08:54 201855 Thread-2: Thu Feb 8 15:08:56 201856 Exiting Thread-257 58 Exiting Main Thread