threading 设置线程超时

def thread1():
    # 线程1
    print('1')
    time.sleep(180)


def thread2():
    # 线程2
    print('2')
    time.sleep(5)
    print('线程2结束')


import threading, time
tasks = []

task1 = threading.Thread(target=thread1)
task1.setDaemon(True) # 设置线程为守护线程,主线程结束,子线程随之结束,不等待
task1.start()
tasks.append(task1)

task2 = threading.Thread(target=thread2)
task2.setDaemon(True)
task2.start()
tasks.append(task2)

for u in tasks:
    # join() 主线程等待子线程结束,一直等待,多线程运行时间等于最长子线程的时间
    u.join(timeout=6) # 设置线程超时,6s 后线程1随之结束

你可能感兴趣的:(python,开发语言)