Daemon 守护线程(27-11)

 

t2.setDaemon(True)不再等待里面的sleep(5)。

当设成setDaemon(True)这个线程就不等了。

  例子一:

import threading
from time import ctime, sleep

def music(func):
  for i in range(2):
    print(func, ctime())      # 1 执行  # 5 执行
    sleep(1)
    print("end music", ctime())  # 4 执行  # 6 执行

def move(func):
  for i in range(2):
    print(func, ctime())      # 2 执行
    sleep(5)
    print("end move", ctime())

 threads = []

 t1 = threading.Thread(target=music,args=("小苹果",))

  threads.append(t1)

  t2 = threading.Thread(target=move,args=("华尔街之狼",))

  threads.append(t2)

  if __name__ == "__main__":

    t2.setDaemon(True)

    for t in threads:

      t.start()

    print("程序执行结束", ctime())    # 3 执行

 

程序运行结果:

小苹果 Fri Sep  7 20:04:24 2018
华尔街之狼 Fri Sep  7 20:04:24 2018
程序执行结束 Fri Sep  7 20:04:24 2018
end music Fri Sep  7 20:04:25 2018
小苹果 Fri Sep  7 20:04:25 2018
end music Fri Sep  7 20:04:26 2018

  ------------------------------------------------------------------------------------------------------

  例子二:

t.setDaemon(True)谁也不等待
import threading
from time import ctime, sleep

def music(func):
  for i in range(2):
    print(func, ctime())      # 1 执行  
    sleep(1)
    print("end music", ctime())  

def move(func):
  for i in range(2):
    print(func, ctime())      # 2 执行
    sleep(5)
    print("end move", ctime())
 threads = []

 t1 = threading.Thread(target=music,args=("小苹果",))

  threads.append(t1)

  t2 = threading.Thread(target=move,args=("华尔街之狼",))

  threads.append(t2)

  if __name__ == "__main__":
    for t in threads:
      t.setDaemon(True)
      t.start()
    print("程序执行结束", ctime())    # 3 执行

程序运行结果:

小苹果 Fri Sep 7 20:18:31 2018
华尔街之狼 Fri Sep 7 20:18:31 2018
程序执行结束 Fri Sep 7 20:18:31 2018

 

posted @ 2018-09-07 21:18  Kay_xs  阅读(121)  评论(0编辑  收藏  举报