学习多线程中,实例代码中有使用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到列表是完全等价的。
因为你的程序(前面省略),等价于:
列表不是必须的。
问题二:
使用join是为了阻塞当前线程(即主线程),直到两个子线程结束。