Click to Visit Homepage : zzyzz.top


Thread Based Parallelism - Thread in a Subclass


  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 = threadID 10 self.name = name 11 self.counter = counter 12 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 -= 1 24 25 if __name__ == '__main__': 26 # Create two threads 27 thread1 = myThread(1, "Thread-1", 1) 28 thread2 = myThread(2, "Thread-2", 2) 29 30 # Start the Threads created 31 thread1.start() 32 thread2.start() 33 34 # Wait for all thread to complete 35 thread1.join() 36 thread2.join() 37 38 print ("Exiting Main Thread") 39 40 Output, 41 Starting Thread-1 42 Starting Thread-2 43 44 Thread-1: Thu Feb 8 15:08:47 2018 45 Thread-1: Thu Feb 8 15:08:48 2018 46 Thread-2: Thu Feb 8 15:08:48 2018 47 Thread-1: Thu Feb 8 15:08:49 2018 48 Thread-2: Thu Feb 8 15:08:50 2018 49 Thread-1: Thu Feb 8 15:08:50 2018 50 Thread-1: Thu Feb 8 15:08:51 2018 51 Exiting Thread-1 52 53 Thread-2: Thu Feb 8 15:08:52 2018 54 Thread-2: Thu Feb 8 15:08:54 2018 55 Thread-2: Thu Feb 8 15:08:56 2018 56 Exiting Thread-2 57 58 Exiting Main Thread

 

posted @ 2018-02-08 15:18  zzYzz  阅读(137)  评论(0编辑  收藏  举报


Click to Visit Homepage : zzyzz.top