thread模块有一个join方法,主线程调用的时候是为了等其余线程结束再执行下面的代码.python
比较下面的结果能够看出来:ubuntu
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前,那么就永远在阻塞了spa