首页 > 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是为了阻塞当前线程(即主线程),直到两个子线程结束。


@jokester 说得对,如果主线程里没有后续操作不join也是可以的。。设置了子线程daemon=True才会在主线程结束的时候强制终止。。


如果你需要线程执行完就要用join()阻塞地等, 不需要可以不等

以这个代码来说先start还是先加入列表不重要, 反正start有异常就死了,

【热门文章】
【热门文章】