python 线程之 threading(二)

时间:2022-10-31 19:51:15

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

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

 import threading
import time def countdown(n):
while n > 0:
print('T-minus', n)
n -= 1
time.sleep(5) t = threading.Thread(target=countdown, args=(10, ))
t.start() if t.is_alive():
print('still alive')
else:
print('complete')

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

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

 import threading
import time def countdown(n):
while n > 0:
print('T-minus', n)
n -= 1
time.sleep(2) t = threading.Thread(target=countdown, args=(10, ))
t.start()
t.join()
print('complete')

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

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

 import threading
import time def countdown(n):
while n > 0:
print('T-minus', n)
n -= 1
time.sleep(2) t = threading.Thread(target=countdown, args=(10, ), daemon=True)
t.start()
print('complete')

运行结果为:

T-minus 10
complete

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

 t = threading.Thread(target=countdown, args=(10, ))
t.setDaemon(daemonic=True)
t.start()