python--基础知识点--线程join、setDaemon

1. join

用于阻塞主线程,直到子线程完成或阻塞主线程超时,主线程继续往下执行。

# 1.直到子线程完成,主线程继续往下执行。
import time
import threading


def my_thread():
    print("my_thread_start")
    time.sleep(2)
    print("my_thread_end")


thread0 = threading.Thread(target=my_thread)
print("====main_thread====")
thread0.start()
thread0.join(3)
print("====main_thread====")


"""
运行结果:
====main_thread====
my_thread_start
my_thread_end
====main_thread====

Process finished with exit code 0
"""
# 直到阻塞主线程超时,主线程继续往下执行。
import time
import threading


def my_thread():
    print("my_thread_start")
    time.sleep(2)
    print("my_thread_end")


thread0 = threading.Thread(target=my_thread)
print("====main_thread====")
thread0.start()
thread0.join(1)
print("====main_thread====")


"""
运行结果:
====main_thread====
my_thread_start
====main_thread====
my_thread_end

Process finished with exit code 0
"""
2. setDaemon

将子线程设置为守护线程,在主线程完成退出时,子线程不论是否完成,跟着主线程一块退出。

import time
import threading


def my_thread():
    print("my_thread_start")
    time.sleep(2)
    print("my_thread_end")


thread0 = threading.Thread(target=my_thread)
print("====main_thread====")
thread0.setDaemon(daemonic=True)
thread0.start()
print("====main_thread====")


"""
运行结果:
====main_thread====
my_thread_start
====main_thread====

Process finished with exit code 0

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值