测试代码
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