python Thread模块 join方法

本文通过两个示例对比展示了Python中threading模块的join方法的作用。解释了如何使用join方法确保主线程等待子线程完成后再继续执行,这对于理解多线程程序的行为至关重要。

thread模块有一个join方法,主线程调用的时候是为了等其他线程结束再执行下面的代码.

比较下面的结果可以看出来:

root@VM-131-71-ubuntu:~/python# cat a.py 
import threading
class x(threading.Thread):
    def __init__(self,i):
        self.a=i
	super(x,self).__init__()
    def run(self):
	print self.a
a1=x(1)
a2=x(2)
a3=x(3)
a1.start()    #start会调用run方法
a2.start()
a3.start()
a1.join()      #等a1的run方法执行完,再执行完下面的语句
a2.join()      
a3.join()
print "xx"
root@VM-131-71-ubuntu:~/python# python a.py 
1
2
3
xx
root@VM-131-71-ubuntu:~/python# cat a.py 
import threading
class x(threading.Thread):
    def __init__(self,i):
        self.a=i
	super(x,self).__init__()
    def run(self):
	print self.a
a1=x(1)
a2=x(2)
a3=x(3)
a1.start()
a2.start()
a3.start()
print "xx"
root@VM-131-71-ubuntu:~/python# python a.py 
1
2
xx                                 #xx输出在3前面,说明没有等a3对象的run方法执行完
3

join方法不能在start方法前,想想看,如果join在start前,那么就永远在阻塞了

转载于:https://my.oschina.net/u/209614/blog/379305

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值