Thread Based Parallelism - Thread in a Subclass

本文展示了一个使用Python threading模块通过子类化Thread类来创建并运行多线程的示例。该示例中定义了一个名为myThread的子类,并在其中实现了run方法。创建了两个线程实例并启动它们,每个线程会打印带有当前时间的消息。

  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

 

转载于:https://www.cnblogs.com/zzyzz/p/8431675.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值