Python主线程和子线程之间的关系

  1. 主线程等待子线程执行完再结束
# 导包
from threading import *
from time import *
def dance():
    print(current_thread())
    for i in range(6):
        print('跳舞...')
        sleep(0.2)


if __name__ == '__main__':
    dance_thread = Thread(target=dance)
    dance_thread.start()
    sleep(0.5)
    print('over')

  1. 主线程结束时直接销毁子线程
# 导包
from threading import *
from time import *
def dance():
    print(current_thread())
    for i in range(6):
        print('跳舞...')
        sleep(0.2)


if __name__ == '__main__':
    # 将该线程设置为守护主线程
    dance_thread = Thread(target=dance)
    dance_thread.setDaemon(True)
    dance_thread.start()
    sleep(0.5)
    print('over')


posted @ 2021-03-09 17:56  code-G  阅读(1132)  评论(0编辑  收藏  举报