Python3 线程中常用的两个模块为:
_thread
threading(推荐使用)
thread 模块已被废弃。用户可以使用 threading 模块代替。所以,在 Python3 中不能再使用"thread" 模块。为了兼容性,Python3 将 thread 重命名为 "_thread"。
函数时调用:
最简单的读线程案例:
#threading模块创建线程实例
#步骤:1.用Thread类创建一个实例 2.实例化后调用start方法启动线程
from threading import Thread
#线程函数
def threadDemo(msg):
print(msg)
if __name__ == '__main__':
#实例化线程类,target参数为线程执行的函数,args参数为线程函数的参数
thread1 = Thread(target=threadDemo,args=('this is a thread demo',))
thread1.start()
输出:this is a thread demo
继承式调用
#步骤:1.继承Thread类创建一个新的子类 2.实例化后调用start方法启动线程
#线程函数
def threadDemo(msg):
print(msg)
class MyThread(Thread):
def __init__(self,msg):
super(MyThread,self).__init__()
self.msg = msg
def run(self):
threadDemo(self.msg)
if __name__ == '__main__':
t1 = MyThread('thread t1')
t2 = MyThread('thread t2')
t1.start()
t2.start()
t1.join()
t2.join()
输出:thread t1
thread t2
线程同步
线程在运行时是相互独立的,线程与线程间互不影响
def print_time(threadName,count,delay):
while count:
time.sleep(delay)
print("%s: %s" % (threadName, time.ctime(time.time())))
count -= 1
class MyThread(Thread):
def __init__(self,name,count):
super(MyThread,self).__init__()
self.name = name
self.count = count
def run(self):
print('线程开始'+self.name)
print_time(self.name,self.count,2)
print('线程结束'+self.name)
if __name__ == '__main__':
th1 = MyThread('th1',5)
th2 = MyThread('th2',5)
th1.start()
th2.start()
th1.join()
th2.join()
print('--主线程结束--')
输出结果:
线程开始th1
线程开始th2
th1: Tue Dec 31 10:25:30 2019
th2: Tue Dec 31 10:25:30 2019
th1: Tue Dec 31 10:25:32 2019
th2: Tue Dec 31 10:25:32 2019
th1: Tue Dec 31 10:25:34 2019
th2: Tue Dec 31 10:25:34 2019
th1: Tue Dec 31 10:25:36 2019
th2: Tue Dec 31 10:25:36 2019
th1: Tue Dec 31 10:25:38 2019
线程结束th1
th2: Tue Dec 31 10:25:38 2019
线程结束th2
--主线程结束--