并发编程——线程——Thread对象的属性和方法
生活随笔
收集整理的這篇文章主要介紹了
并发编程——线程——Thread对象的属性和方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Thread實例對象的方法
# isAlive(): 返回線程是否活動的。# getName(): 返回線程名。# setName(): 設置線程名。threading模塊提供的一些方法:
# threading.currentThread(): 返回當前的線程變量。# threading.enumerate(): 返回一個包含正在運行的線程的list。正在運行指線程啟動后、結束前,不包括啟動前和終止后的線程。# threading.activeCount(): 返回正在運行的線程數量,與len(threading.enumerate())有相同的結果。 import threading from threading import Threaddef task():import timetime.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 Threaddef 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 = Truethread1.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沒有輸出。
總結
以上是生活随笔為你收集整理的并发编程——线程——Thread对象的属性和方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 并发编程——线程——线程的理论和创建以及
- 下一篇: 并发编程——线程——CPython的GI