Python 系列文章 —— 线程详解

2022-01-13 10:56:17 浏览数 (1)

  • new#创建线程-构造器方式 import time import threading def work(num): print('线程名称:',threading.current_thread().getName(),'参数:',num,'开始时间:',time.strftime('%Y-%m-%d %H:%M:%S')) if __name__ == '__main__': print('主线程开始时间:',time.strftime('%Y-%m-%d %H:%M:%S')) t1 = threading.Thread(target=work,args=(3,)) t2 = threading.Thread(target=work,args=(2,)) t3 = threading.Thread(target=work,args=(1,)) t1.start() t2.start() t3.start() t1.join() t2.join() t3.join() print('主线程结束时间:', time.strftime('%Y-%m-%d %H:%M:%S')) #创建线程-继承方式 class MyThread(threading.Thread): def __init__(self,num): super().__init__() self.num = num def run(self): print('线程名称:', threading.current_thread().getName(), '参数:', self.num, '开始时间:', time.strftime('%Y-%m-%d %H:%M:%S')) if __name__ == '__main__': print('主线程开始时间:',time.strftime('%Y-%m-%d %H:%M:%S')) t1 = MyThread(3) t2 = MyThread(2) t3 = MyThread(1) t1.start() t2.start() t3.start() t1.join() t2.join() t3.join() print('主线程结束时间:', time.strftime('%Y-%m-%d %H:%M:%S'))
  • daemonimport threading def work(num): for i in range(num): print(threading.current_thread().name " " str(i)) t = threading.Thread(target=work, args=(10,), name='守护线程') #t.daemon = True t.start() for i in range(10): pass
  • localimport threading import time # 不使用 threading.local num = 0 def work(): global num for i in range(10): num = 1 print(threading.current_thread().getName(), num) time.sleep(0.0001) for i in range(5): threading.Thread(target=work).start() # 使用 threading.local num = threading.local() def work(): num.x = 0 for i in range(10): num.x = 1 print(threading.current_thread().getName(), num.x) time.sleep(0.0001) for i in range(5): threading.Thread(target=work).start()
  • timer
代码语言:python代码运行次数:0复制
from threading import Timer
import time
#定时器-单次执行
# def work():
#     print("Hello Python")
# # 5 秒后执行 work 方法
# t = Timer(5, work)
# t.start()

#定时器-重复执行
count = 0
def work():
    print('当前时间:', time.strftime('%Y-%m-%d %H:%M:%S'))
    global t, count
    count  = 1
    # 如果 count 小于 5,开始下一次调度
    if count < 5:
        t = Timer(1, work)
        t.start()
# 指定 2 秒后执行 work 方法
t = Timer(2, work)
t.start()

0 人点赞