python thread SetDaemon 用法 测试

python2 :
源码如下:

#!/usr/bin/python
#-*- coding:utf-8 -*-
import sys
import threading

import time

class TaskThread(threading.Thread):
    def __init__(self, cnt):
        threading.Thread.__init__(self)
        self.cnt = cnt
    def run(self):

        while self.cnt:
            time.sleep(1)
            print("cnt = %d\n" % self.cnt)
            self.cnt = self.cnt - 1

        print('task thread exit!\n')


if __name__ == "__main__":
    task = TaskThread(10)
    task.setDaemon(True)
    task.start()
    num = 5

    while num:
        time.sleep(1)
        print("num = %d\n" % num)
        num = num - 1

    print('Main Process Exit\n')

运行结果如下:

C:\Python27\python.exe E:/python/work/thread_t1/thread_test1.py
num = 5
cnt = 10


num = 4
cnt = 9


num = 3
cnt = 8


num = 2
cnt = 7


num = 1
cnt = 6


Main Process Exit


Process finished with exit code 0

代码修改为如下形式,
注释掉:task.setDaemon(True)

#!/usr/bin/python
#-*- coding:utf-8 -*-
import sys
import threading

import time

class TaskThread(threading.Thread):
    def __init__(self, cnt):
        threading.Thread.__init__(self)
        self.cnt = cnt
    def run(self):

        while self.cnt:
            time.sleep(1)
            print("cnt = %d\n" % self.cnt)
            self.cnt = self.cnt - 1

        print('task thread exit!\n')


if __name__ == "__main__":
    task = TaskThread(10)
    #task.setDaemon(True)
    task.start()
    num = 5

    while num:
        time.sleep(1)
        print("num = %d\n" % num)
        num = num - 1

    print('Main Process Exit\n')

运行结果:

C:\Python27\python.exe E:/python/work/thread_t1/thread_test1.py
cnt = 10
num = 5


cnt = 9
num = 4


num = 3
cnt = 8


cnt = 7
num = 2


num = 1
cnt = 6


Main Process Exit

cnt = 5

cnt = 4

cnt = 3

cnt = 2

cnt = 1

task thread exit!


Process finished with exit code 0

后台线程与前台线程的直接区别是,
1)setDaemon(True): 当主线程退出时,后台线程随机退出;
2)setDaemon(False)(默认情况): 当主线程退出时,若前台线程还未结束,则等待所有线程结束,相当于在程序末尾加入join().

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐