近期对线程做了研究,发现对于Join()函数理解比较难,在多次亲手实践后,方才豁然开朗,特分享给大家:
#coding=utf-8
import thread, Queue, threading
from time import sleep, ctime
loops = [4,2]
work_queue = Queue.Queue()
class Producer(threading.Thread):
def __init__(self, work_queue):
super(Producer, self).__init__() # 必须调用
self.work_queue = work_queue
def run(self):
#print("Begin produce...")
num = 1
while num<6:
self.work_queue.put(str(num))
num = num+1
sleep(1) # 暂停1秒
class loopn(threading.Thread):
def __init__(self, name, work_queue, sleeptime):
super(loopn, self).__init__() # 必须调用
self.work_queue = work_queue
self.name = name
self.sleeptime = sleeptime
def run(self):
sleep(1)
a=self.work_queue.get()
print 'loop:', self.name, ' start at:', ctime(), a
sleep(self.sleeptime)
a=self.work_queue.get()
print 'loop:', self.name, ' done at:', ctime(), a
def main():
work_queue = Queue.Queue()
print 'producter start:', ctime()
producer = Producer(work_queue)
producer.daemon = True # 当主线程退出时子线程也退出
producer.start()
producer.join()
sleep(2)
num=work_queue.get()
print 'start_get:',num
loopn0 = loopn('loop0',work_queue,4)
# loopn0.daemon = True # 当主线程退出时子线程也退出
loopn1 = loopn('loop1',work_queue,2)
loopn1.daemon = True # 当主线程退出时子线程也退出
loopn0.start()
loopn1.start()
# loopn0.join()
loopn1.join()
print 'all end:', ctime()
if __name__ == '__main__':
main()
上述结果是怎样的呢?看结果如下:
producter start: Mon Aug 31 19:09:36 2015
start_get: 1
loop:loop: loop1 start at:loop0 start at: Mon Aug 31 19:09:44 2015 2
Mon Aug 31 19:09:44 2015 3
loop: loop1 done at: Mon Aug 31 19:09:46 2015 4
all end: Mon Aug 31 19:09:46 2015
loop: loop0 done at: Mon Aug 31 19:09:48 2015 5
总结一下,join有以下几个关键点需要注意:
1. join()会等到该线程结束才执行后面的语句,当然给了 timeout 参数的时候例外。
2. 一旦线程启动后,就会一直运行到线程的函数结束,才会自然退出,除非daemon设置为True
如果将主程序中的loop1.join()也#掉,结果又是如何,反之,如果将loop0.join() 和 loopn0.daemon = True前的#拿掉又会如何,试试就马上明白了~
实际上理解上述两点,Join学习就算基本过关啦~