使用线程完成多任务需要导入threading包:import threading
1.线程类Thread参数说明:
Thread([group [, target [, name [, args [, kwargs]]]]])
- group: 线程组,目前只能使用None
- target: 执行的目标任务名
- args: 以元组的方式给执行任务传参
- kwargs: 以字典方式给执行任务传参
- name: 线程名,一般不用设置
2.启动线程
启动线程使用start()方法, sub_thread.start()
3.线程注意点:
- 线程的执行顺序是无序的
- 主线程默认会等待所有的子线程结束后才结束
- 可以设置守护线程,当主线程结束时,子线程立即结束
4.设置守护主线程
# 设置成为守护主线程,主线程退出后子线程直接销毁不再执行子线程的代码
sub_thread = threading.Thread(target=run, daemon=True)
# 守护主线程方式二
# sub_thread.setDaemon(True)
5.获取当前程序的活动线程列表
thread_list = threading.enumerate()
print(thread_list)
6.自定义线程
import threading
import time
class MyThread(threading.Thread):
def __init__(self,count1, count2):
# 重写父类__init__方法
# 自定义线程类需要继承父类的构造方法
super().__init__()
self.count1 = count1
self.count2 = count2
# 定义成静态方法
@staticmethod
def task1(count):
print("task1",threading.current_thread())
for i in range(count):
print("任务1执行")
time.sleep(0.2)
@staticmethod
def task2(count):
print("task2",threading.current_thread())
for i in range(count):
print("任务2执行")
time.sleep(0.2)
# task1与task2属于同一个线程,顺序执行
def run(self):