threading模块
(1).Thread线程类
【1】构造:
--1.Thread(target = 目标函数, args = (参数,))
--2.自定义Thread派生类,重写run方法逻辑
【2】.start() 启动线程
【3】.join() 要求主线程等待
【4】.current_thread() 获取当前线程
【5】.name 线程名称
import time
import threading
//方法1
def worker(n):
print('{threading.current_thread().name}函数执行开始于:{}'.format(time.ctime()))
time.sleep(n)
print('{threading.current_thread().name}函数执行结束于:{}'.format(time.ctime()))
def main():
print(f'[住函数执行开始于:{time.ctime()}]')
threads = []
t1 = threading.Thread(target = worker, args = (4,))
threads.append(t1)
t2 = threading.Thread(target = worker, args = (2,))
threads.append(t2)
for t in threads:
t.start()
for t in threads:
t.join() //告诉主线程等待当前线程执行完毕
print(f'[住函数执行结束于:{time.ctime()}]')
//方法2
def worker(n):
print('{threading.current_thread().name}函数执行开始于:{}'.format(time.ctime()))
time.sleep(n)
print('{threading.current_thread().name}函数执行结束于:{}'.format(time.ctime()))
class MyThread(threading.Thread):
def __init__(selffunc,args):
threading.Thread.__init__(self)
self.func = func
self.args = args
def run(self):
self.func(*self.args)
def main():
print(f'[住函数执行开始于:{time.ctime()}]')
threads = []
t1 = MyThread(worker, (4,))
threads.append(t1)
t1 = MyThread(worker, (2,))
threads.append(t2)
for t in threads:
t.start()
for t in threads:
t.join() //告诉主线程等待当前线程执行完毕
print(f'[住函数执行结束于:{time.ctime()}]')