# 使用线程的注意点
# 1. 线程执行的时候是无序的
# 2. 主线程会等待所有的子线程执行完成以后程序再退出
import threading
import time
# 测试多个线程执行的时候查看是否有序
def show():
for i in range(5):
print(i, threading.current_thread())
time.sleep(0.2)
# 测试主线程是否会等待子线程执行完成以后程序再退出
def test():
for i in range(5):
print("test:", i)
time.sleep(0.5)
def test1():
for i in range(5):
print("test1:", i)
time.sleep(1)
if __name__ == '__main__':
# 模拟大量线程取值show任务
# for i in range(5):
# sub_thread = threading.Thread(target=show)
# sub_thread.start()
# 创建子线程, daemon=True 守护主线程, 主线程退出后子线程直接销毁不再执行子线程的代码
# sub_thread = threading.Thread(target=test, daemon=True)
sub_thread = threading.Thread(target=test)
# 设置成为守护主线程,主线程退出后子线程直接销毁不再执行子线程的代码
sub_thread.setDaemon(True)
# 扩展: 守护主线程
sub_thread.start()
three_thread = threading.Thread(target=test1)
# 设置成为守护主线程,主线程退出后子线程直接销毁不再执行子线程的代码
three_thread.setDaemon(True)
three_thread.start()
# 主线程延时1秒
time.sleep(1)
print("over")
exit()
python,线程-守护主线程,Daemon
猜你喜欢
转载自blog.csdn.net/great_zhou/article/details/81050644
今日推荐
周排行