Thread实例对象的方法
# isAlive(): 返回线程是否活动的。
# getName(): 返回线程名。
# setName(): 设置线程名。
threading模块提供的一些方法:
# threading.currentThread(): 返回当前的线程变量。
# threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。
# threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。
import threading
from threading import Thread
def task():
import time
time.sleep(2)
print("Thread name =", threading.current_thread().getName())
if __name__ == '__main__':
thread = Thread(target=task)
thread.start()
print("Before join thread is alive:", thread.is_alive())
thread.join()
print("After join thread is alive:", thread.is_alive())
print("Threading enumerate:", threading.enumerate())
print("Threading active count:", threading.active_count())
print("MainThread:", threading.current_thread())
print("MainThread name:", threading.current_thread().getName())
输出结果为:
Before join thread is alive: True
Thread name = Thread-1
After join thread is alive: False
Threading enumerate: [<_MainThread(MainThread, started 3868)>]
Threading active count: 1
MainThread: <_MainThread(MainThread, started 3868)>
MainThread name: MainThread
守护线程
无论是进程还是线程,都遵循:守护xxx会等待主xxx运行完毕后被销毁。
需要强调的是:运行完毕并非终止运行,对主进程来说,运行完毕指的是主进程代码运行完毕,对主线程来说,运行完毕指的是主线程所在的进程内所有非守护线程统统运行完毕,主线程才算运行完毕。
主进程在其代码结束后就已经算运行完毕了(守护进程在此时就被回收),然后主进程会一直等非守护的子进程都运行完毕后回收子进程的资源(否则会产生僵尸进程),才会结束。
主线程在其他非守护线程运行完毕后才算运行完毕(守护线程在此时就被回收),因为主线程的结束意味着进程的结束,进程整体的资源都将被回收,而进程必须保证非守护线程都运行完毕后才能结束。
来看一个例子验证一下我们的说法:
import time
from threading import Thread
def thread1():
print("Thread 1 is start.")
time.sleep(1)
print("Thread 1 is done.")
def thread2():
print("Thread 2 is start.")
time.sleep(2)
print("Thread 2 is done.")
if __name__ == '__main__':
thread1 = Thread(target=thread1)
thread2 = Thread(target=thread2)
thread2.daemon = True
thread1.start()
thread2.start()
print("Under thread 1 and thread 2 start.")
输出结果为:
Thread 1 is start.
Thread 2 is start.
Under thread 1 and thread 2 start.
Thread 1 is done.
thread2是守护线程,也就是说thread2会等到除主线程之外的非守护线程全死了之后才死,thread1睡一秒,就结束,而thread2要睡两秒,所以当thread2还在沉睡的时候thread1就已经死了,非守护进程thread1死了之后,主线程也跟着死了,主线程一死,守护线程thread2也得死,所以Thread 2 id done没有输出。