风-fmgao

导航

守护线程

#!/usr/bin/env python
# encoding: utf-8  
# Date: 2018/6/18


# from threading import Thread
# import time
#
#
# def sayhi(name):
#     time.sleep(2)
#     print('%s say hello' % name)
#
#
# if __name__ == '__main__':
#     t = Thread(target=sayhi, args=('egon', ))
#     t.setDaemon(True)  # 等价于t.daemon = True
#     t.start()
#
#     print('主线程')
#     print(t.is_alive())  # True

# 主线程必须是非守护线程运行完毕才停止
from threading import Thread
import time


def foo():
    print(123)
    time.sleep(2)  # 与非守护线程时间一样的时候就不会执行
    print('end123')


def bar():
    print(456)
    time.sleep(3)
    print('end456')


if __name__ == '__main__':
    t1 = Thread(target=foo)
    t2 = Thread(target=bar)

    t1.daemon = True
    t1.start()
    t2.start()
    print('main----------------')

posted on 2018-06-18 10:18  风-fmgao  阅读(108)  评论(0编辑  收藏  举报