zoukankan      html  css  js  c++  java
  • python 线程之 threading(二)

     http://www.cnblogs.com/someoneHan/p/6204640.html 线程一中对threading线程的开启调用做了简单的介绍

    1 在线程开始之后,线程开始独立的运行直到目标函数返回为止。如果需要在主线程中判断开启的线程是否在运行可以使用 is_alive()方法:

     1 import threading
     2 import time
     3 
     4 def countdown(n):
     5     while n > 0:
     6         print('T-minus', n)
     7         n -= 1
     8         time.sleep(5)
     9 
    10 t = threading.Thread(target=countdown, args=(10, ))
    11 t.start()
    12 
    13 if t.is_alive():
    14     print('still alive')
    15 else:
    16     print('complete')
    View Code

      使用is_alive() 判断线程是否使完成状态

    2. 还可以使用join链接到当前线程上,那么当前线程会登台线程完成之后在运行

     1 import threading
     2 import time
     3 
     4 def countdown(n):
     5     while n > 0:
     6         print('T-minus', n)
     7         n -= 1
     8         time.sleep(2)
     9 
    10 t = threading.Thread(target=countdown, args=(10, ))
    11 t.start()
    12 t.join()
    13 print('complete')
    View Code

     这样的代码在t线程运行结束之后才会继续运行print函数

    3. 守护线程:使用threading.Thread创建出来的线程在主线程退出之后不会自动退出。如果想在主线程退出的时候创建的线程也随之退出

     1 import threading
     2 import time
     3 
     4 def countdown(n):
     5     while n > 0:
     6         print('T-minus', n)
     7         n -= 1
     8         time.sleep(2)
     9 
    10 t = threading.Thread(target=countdown, args=(10, ), daemon=True)
    11 t.start()
    12 print('complete')
    View Code

     运行结果为:

    T-minus 10
    complete

    另外一种设置为守护线程的方式为调用setDaemon()方法。

    1 t = threading.Thread(target=countdown, args=(10, ))
    2 t.setDaemon(daemonic=True)
    3 t.start()
    View Code
  • 相关阅读:
    玩转spring boot——结合JPA事务
    玩转spring boot——结合AngularJs和JDBC
    玩转spring boot——结合jQuery和AngularJs
    028_Mac急救箱快捷键
    006_身体部位名词
    005_Philippines之行准备
    027_MacOs上如何将多页word打印到一个页面上
    026_PPT知识汇总
    025_Excel知识汇总
    024_Word知识汇总
  • 原文地址:https://www.cnblogs.com/someoneHan/p/6209240.html
Copyright © 2011-2022 走看看