python的多线程是假多线程,本质是交叉串行,并不是严格意义上的并行,或者可以这样说,不管怎么来python的多线程在同一时间有且只有一个线程在执行(举个例子,n个人抢一个座位,但是座位就这一个,不管怎么抢同一时间只有一个人在座位上可能前一秒是a在座位上座,后一秒b就给抢去了)
多线程大体上有两种实现方式
1.继承
threading模块
建立一个类然后继承这个类threading.Thread
import threading# 创建动作类继承threading.Thread
class MyThread(threading.Thread):def __init__(self, name):threading.Thread.__init__(self, name=name)# 重写run方法,此时run方法里面的动作就是此线程会执行的动作def run(self):print('thread {} is running'.format(self.name))temp_list = ['thread1', 'thread2']
t1 = MyThread('thread1')
t2 = MyThread('thread2')temp1 = [MyThread(t) for t in temp_list]
temp2 = [s.start() for s in temp1]
temp3 = [j.join() for j in temp1]
2.线程类传参
import threading
import timedef worker(a, b):while True:print('Worker thread running {} {}'.format(a, b))time.sleep(1)a = 123
b = "hahaha"
# 创建守护线程
t = threading.Thread(target=worker, args=(a, b, ), daemon=True)
# 启动线程
t.start()
# join()调用之后程序会等到此线程结束后再执行t.join()后面主线程的代码
t.join()# 主线程执行一些操作
print('Main thread running')
time.sleep(5)
print('Main thread finished')