Python Thread join() daemon()

join()

# 自定义线程要执行的函数
def test(*args):
    for info in args:
        print(threading.current_thread().getName() +" "+ info)

if __name__ == '__main__':
    t_tuple = ("春","夏","秋","冬")
    # 创建协程对象,不传参
    thread_1 = threading.Thread(target=test,args=t_tuple)
    # 启动线程1
    thread_1.start()

    for i in range(4):
        print(threading.current_thread().getName())

结果
Thread-1 春MainThread

Thread-1 夏MainThread

Thread-1 秋MainThread

Thread-1 冬MainThread

使用Thread创建了一个线程(线程名为Thread-1),该线程会执行上面的test()函数。if name == ‘main’: 下面为主线程,子线程在执行的时候主线程会继续向下执行的任务。而主线程MainThread和子线程Thread-1会轮流获取CPU资源。因此获取的输出结果有一定的顺序。

如果我们想让子线程先执行完再让主线程继续向下执行,可以调用线程对象的join()方法即可

thread.join( [timeout] )

timeout 参数作为可选参数,其功能是指定 thread 线程最多可以占用 CPU 资源的时间(以秒为单位),如果省略,则默认直到 子线程 执行结束才释放 CPU 资源。

def test(*args):
    for info in args:
        print(threading.current_thread().getName() +" "+ info)

if __name__ == '__main__':
    t_tuple = ("春","夏","秋","冬")
    # 创建协程对象,不传参
    thread_1 = threading.Thread(target=test,args=t_tuple)
    # 启动线程1
    thread_1.start()
    thread_1.join()

    for i in range(4):
        print(threading.current_thread().getName())

结果
Thread-1 春
Thread-1 夏
Thread-1 秋
Thread-1 冬
MainThread
MainThread
MainThread
MainThread

由输出结果可看出,子线程执行完之后主线程才会继续向下执行

daemon()

当程序中拥有多个以上线程时,主线程执行结束并不会影响子线程继续执行。换句话说,只有程序中所有线程全部执行完毕后,程序才算真正结束。(参考上面)

中还可以创建另一种线程,称为守护线程,当程序中主线程执行完毕后,未执行完的线程会不在执行

# 自定义线程要执行的函数
def test():
    for info in range(10000):
        print(threading.current_thread().getName() +" "+ str(info))

if __name__ == '__main__':
    # 创建协程对象,不传参
    thread_1 = threading.Thread(target=test)
    # 将thread设置为守护线程
    thread_1.daemon = True
    # 启动线程1
    thread_1.start()
    
    for i in range(4):
        print(threading.current_thread().getName())

结果
Thread-1 0MainThread

Thread-1 1MainThread

Thread-1 2MainThread

Thread-1 3MainThread

Thread-1 4

调用 thread 线程的 daemon 属性并赋值为 True,则该 thread 线程就变成了守护线程。由于该程序中除了 thread 守护线程就只有主线程 MainThread,因此只要主线程执行结束,则守护线程将随之消亡。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

季布,

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值