Python3 线程中常用的两个模块为:
- _thread
- threading(推荐使用)
使用Thread类创建
说明:主线程会等待所有的子线程结束后才结束1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34import threading
from time import sleep,ctime
def sing():
for i in range(3):
print("正在唱歌...%d"%i)
sleep(1)
def dance():
for i in range(3):
print("正在跳舞...%d"%i)
sleep(1)
if __name__ == '__main__':
print('---开始---:%s'%ctime())
t1 = threading.Thread(target=sing)
t2 = threading.Thread(target=dance)
t1.start()
t2.start()
#sleep(5) # 屏蔽此行代码,试试看,程序是否会立马结束?
print('---结束---:%s'%ctime())
"""
输出结果:
---开始---:Sat Aug 24 08:44:21 2019
正在唱歌...0
正在跳舞...0---结束---:Sat Aug 24 08:44:21 2019
正在唱歌...1
正在跳舞...1
正在唱歌...2
正在跳舞...2
"""
使用Thread子类创建
为了让每个线程的封装性更完美,所以使用threading模块时,往往会定义一个新的子类class,只要继承threading.Thread就可以了,然后重写run方法。
1 | import threading |
使用线程池ThreadPoolExecutor创建
1 | from concurrent.futures import ThreadPoolExecutor |
__END__

文章作者:三国小梦
文章出处:python线程的几种创建方式
作者签名:简单地活着, 肆意又精彩.
关于主题:Hexo - Live For Code
版权声明:文章除特别声明外,均采用 BY-NC-SA 许可协议,转载请注明出处
文章出处:python线程的几种创建方式
作者签名:简单地活着, 肆意又精彩.
关于主题:Hexo - Live For Code
版权声明:文章除特别声明外,均采用 BY-NC-SA 许可协议,转载请注明出处