When you use python to develop or test, you will inevitably use python's multi-threading operation. Let me briefly introduce the two basic implementation methods of multi-threading:
[Explanation] :
(1) The third-party library we need to use in multi-threading is threading;
(2) The thread must be attached to the process;
(3) The thread will be automatically released after execution.
Method 1 : Object-oriented method to implement multi-threading
# -*- coding: utf-8 -*-
import threading
class CThread (threading.Thread):
def __init__(self, n):
threading.Thread.__init__(self) #重写父类方法
self.num = n
def run(self):
print(self.num)
if __name__ == "__main__":
a = CThread(1) # 开启一个线程
a.start() # 启动线程
# 开启多个线程
# for i in range(6):
# a = CThread(i) # 连续开启多个线程
# a.start() # 启动线程
Method 2: Process-oriented method to implement multi-threading
import threading
import time
def download(i):
print('开始下载文件%d'%i)
time.sleep(1)
print('文件下载完成')
if __name__=='__main__':
#多线程
for i in range(5):#利用循环创建5个线程
t=threading.Thread(target=download,args=(i,))
print(len(threading.enumerate())) #查看线程数量和进程数量总和
#启动线程
t.start()