Python threading模块简介
Python 提供了两个多线程模块,即 _thread 和 threading。_thread 模块提供低级的接口,用于支持小型的进程线程;threading 模块则以 thread 模块为基础,提供高级的接口。更推荐使用 threading 模块。
threading模块的函数如下:
每一个threading.Thread类对象都有以下方法:
下面的示例直接从 threading.Thread 类继承创建一个新的子类,并实例化后调用 start() 方法启动新线程,即它调用了线程的 run() 方法。
【实例】使用 threading 模块创建多线程
保存并运行程序,输出结果如下:
threading模块的函数如下:
- threading.activeCount():返回活动中的线程对象数目。
- threading.currentThread():返回目前控制中的线程对象。
- threading.enumerate():返回活动中的线程对象列表。
每一个threading.Thread类对象都有以下方法:
- threadobj.start():执行 run() 方法。
- threadobj.run():此方法被 start() 方法调用。
- threadobj.join([timeout]):此方法等待线程结束。timeout 的单位是秒。
- threadobj.isAlive ():返回线程是否是活动的。
- threadobj.getName():返回线程名。
- threadobj.setName():设置线程名。
下面的示例直接从 threading.Thread 类继承创建一个新的子类,并实例化后调用 start() 方法启动新线程,即它调用了线程的 run() 方法。
【实例】使用 threading 模块创建多线程
- import threading
- import time
- exitFlag = 0
- class myThread (threading.Thread):
- def __init__(self, threadID, name, counter):
- threading.Thread.__init__(self)
- self.threadID = threadID
- self.name = name
- self.counter = counter
- def run(self):
- print ("开始线程:" + self.name)
- print_time(self.name, self.counter, 5)
- print ("退出线程:" + self.name)
- def print_time(threadName, delay, counter):
- while counter:
- if exitFlag:
- threadName.exit()
- time.sleep(delay)
- print ("%s: %s" % (threadName, time.ctime(time.time())))
- counter -= 1
- # 创建新线程
- thread1 = myThread(1, "线程1", 1)
- thread2 = myThread(2, "线程2", 2)
- # 开启新线程
- thread1.start()
- thread2.start()
- thread1.join()
- thread2.join()
- 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
退出主线程