Leif160519的blog Leif160519的blog

——————

目录
Python——threading同时运行多个线程实例讲解
/  

Python——threading同时运行多个线程实例讲解


Python里面经常会用到多线程,即所有的方法在同一时间开始运行,而不是按顺序一个一个运行。所用到的模块为threading,下面详解threading用法。

一、我们写三个方法,one、two、three并正常运行。

这里只截图了one()方法,two、three与one内容一样。
image.png

按下面图中的运行方式,三个函数是分别在不同时间运行的。
image.png

这种方式三个函数时在不同时间运行的

二、用threading使三个方法在同一时间运行

定义一个线程池并把要运行的线程one()/two()/three()都写到这个线程池列表里:

threads = []#定义一个线程池
t1 = threading.Thread(target=one,args=(,))#建立一个线程并且赋给t1,这个线程指定调用方法one,并且不带参数
threads.append(t1)#把t1线程装到threads线程池里
t2 = threading.Thread(target=two)
threads.append(t2)
t3 = threading.Thread(target=three)
threads.append(t3)

这时threads这个列表中就有三个线程装在里面了。

下面就是运行这个线程池里面的线程

for t in threads:

用一个for语句遍历threads里的线程,然后调用start()方法运行

注意t.join()必须放在for语句外面。

三、运行结果为在同一时间启动的

结果每个循环都是在同一个时间运行


“The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time.” – Tom Cargill

标  题Python——threading同时运行多个线程实例讲解
作  者Leif160519
出  处https://github.icu/articles/2019/10/08/1570524113361.html
关于博主:坐标南京,运维工程师,如有问题探讨可以直接下方留言。
声援博主:如果您觉得文章对您有帮助,可以评论、订阅、收藏。您的鼓励是博主的最大动力!