threading的join功能

you can go here to see the details.

 

我的理解:使用join后,使主线程执行完后(挂起),子线程再执行完后,主线程才结束。否则主线程会直接结束导致子线程不会执行。

 

import time
import threading


def testRun():
    print('-----start-----')     # 1. 执行
    time.sleep(2)    # 2. 阻塞(挂起,执行下一个线程:1和2步循环,直到所有线程都执行完 1,然后接着往下执行3)
    print(f"当前线程名字:{threading.current_thread().name}")  # 3  (3和4循环,直到所有线程都执行完3,然后接着往下执行5...)
    time.sleep(2)  # 4
    print('qeada')  # 5


thread_list = []
start = time.time()
for i in range(5):
    t = threading.Thread(target=testRun)
    thread_list.append(t)
for t in thread_list:
    t.setDaemon(True)
    t.start()
for t in thread_list:  # 不使用join,会导致所有子线程遇到阻塞后,主线程并不会等待子线程阻塞结束而直接结束。
    t.join()  
print("it's over.")
print(f"总耗时:{time.time()-start}")

>>>
-----start-----
-----start-----
-----start-----
-----start-----
-----start-----
当前线程名字:Thread-1
当前线程名字:Thread-2
当前线程名字:Thread-4
当前线程名字:Thread-3
当前线程名字:Thread-5
qeada
qeada
qeada
qeada
qeada
it's over.
总耗时:4.006011962890625

 

posted on 2018-09-05 10:14 .Tang 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/tangpg/p/9590501.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值