python中的thread_Python中的thread

本文详细介绍了如何在Python中使用threading模块创建和管理线程,重点讲解了守护线程(setDaemon)和join方法的作用。实验结果显示,守护线程在主线程退出时会被自动终止,而join方法用于同步主线程等待子线程完成。

测试代码

import threading

import time

def do_thread_test():

print 'start thread time:', time.strftime('%H:%M:%S')

time.sleep(5)

print 'stop thread time:', time.strftime('%H:%M:%S')

threads = []

for i in range(2):

thread1 = threading.Thread(target=do_thread_test)

thread1.setDaemon(True)

threads.append(thread1)

for t in threads:

t.start()

for t in threads:

t.join()

print 'stop main thread', time.strftime('%H:%M:%S')

注释掉join,注释掉setDaemon(或设置为False),执行结果

start thread time: 21:57:40

start thread time: 21:57:40

stop main thread 21:57:40 主

stop thread time: 21:57:45

stop thread time: 21:57:45

注释掉join,设置setDaemon=True,执行结果

start thread time: 21:59:47

start thread time: 21:59:47

stop main thread 21:59:47

join方法的作用是阻塞,等待子线程结束

join无参数,注释掉setDaemon(或设置为True/False),执行结果

start thread time: 22:02:00

start thread time: 22:02:00

stop thread time: 22:02:05

stop thread time: 22:02:05

stop main thread 22:02:05 主

阻塞时间为time*thread_num

join参数为1,注释掉setDaemon(或设置为False),执行结果

start thread time: 22:11:22

start thread time: 22:11:22

stop main thread 22:11:24

stop thread time: 22:11:27

stop thread time: 22:11:27

join参数为1,设置setDaemon=True,执行结果(阻塞time*thread_num)

start thread time: 22:12:38

start thread time: 22:12:38

stop main thread 22:12:40

原文链接:https://blog.youkuaiyun.com/weixin_44961798/article/details/108269495

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值