python-不能理解多线程中为什么要使用Thread.join()?
本文介绍了python-不能理解多线程中为什么要使用Thread.join()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
学习多线程中,实例代码中有使用join()
这个函数。
# 引入互斥锁
threadLock = threading.Lock()
threads = []
# 创建新线程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# 开启新线程
thread1.start()
thread2.start()
# 添加线程到线程列表
threads.append(thread1)
threads.append(thread2)
# 等待所有线程完成
for t in threads:
t.join()
print "Exiting Main Thread"
请问能解释一下为什么要在线程start()
了之后才加入县城列表?
还有就是为什么要使用join()
来阻塞线程?
解决方案
问题一:
在start前面还是后面append到列表是完全等价的。
因为你的程序(前面省略),等价于:
# 开启新线程
thread1.start()
thread2.start()
# 等待所有线程完成
thread1.join()
thread2.join()
print "Exiting Main Thread"
列表不是必须的。
问题二:
使用join是为了阻塞当前线程(即主线程),直到两个子线程结束。
这篇关于python-不能理解多线程中为什么要使用Thread.join()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文