首页 > 编程笔记 > Python笔记 阅读:48

Python threading模块简介

通义灵码
Python 提供了两个多线程模块,即 _thread 和 threading。_thread 模块提供低级的接口,用于支持小型的进程线程;threading 模块则以 thread 模块为基础,提供高级的接口。更推荐使用 threading 模块。

threading模块的函数如下:
每一个threading.Thread类对象都有以下方法:
下面的示例直接从 threading.Thread 类继承创建一个新的子类,并实例化后调用 start() 方法启动新线程,即它调用了线程的 run() 方法。

【实例】使用 threading 模块创建多线程
  1. import threading
  2. import time
  3.   
  4. exitFlag = 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 ("开始线程:" + self.name)
  14. print_time(self.name, self.counter, 5)
  15. print ("退出线程:" + self.name)
  16.   
  17. def print_time(threadName, delay, counter):
  18. while counter:
  19. if exitFlag:
  20. threadName.exit()
  21. time.sleep(delay)
  22. print ("%s: %s" % (threadName, time.ctime(time.time())))
  23. counter -= 1
  24.   
  25. # 创建新线程
  26. thread1 = myThread(1, "线程1", 1)
  27. thread2 = myThread(2, "线程2", 2)
  28.   
  29. # 开启新线程
  30. thread1.start()
  31. thread2.start()
  32. thread1.join()
  33. thread2.join()
  34. print ("退出主线程")
保存并运行程序,输出结果如下:

开始线程:线程1开始线程:线程2 
线程1: Wed Jan  5 12:02:38 2022
线程2: Wed Jan  5 12:02:39 2022线程1: Wed Jan  5 12:02:39 2022
  
线程1: Wed Jan  5 12:02:40 2022
线程2: Wed Jan  5 12:02:41 2022线程1: Wed Jan  5 12:02:41 2022
  
线程1: Wed Jan  5 12:02:42 2022
退出线程:线程1
线程2: Wed Jan  5 12:02:43 2022
线程2: Wed Jan  5 12:02:45 2022
线程2: Wed Jan  5 12:02:47 2022
退出线程:线程2
退出主线程

相关文章