python中threading超線程用法實例分析
本文實例講述了python中threading超線程用法。分享給大家供大家參考。具體分析如下:
threading基于Java的線程模型設計。鎖(Lock)和條件變量(Condition)在Java中是對象的基本行為(每一個對象都自帶了鎖和條件變量),而在Python中則是獨立的對象。Python Thread提供了Java Thread的行為的子集;沒有優(yōu)先級、線程組,線程也不能被停止、暫停、恢復、中斷。Java Thread中的部分被Python實現了的靜態(tài)方法在threading中以模塊方法的形式提供。
threading 模塊提供的常用方法:
threading.currentThread(): 返回當前的線程變量。
threading.enumerate(): 返回一個包含正在運行的線程的list。正在運行指線程啟動后、結束前,不包括啟動前和終止后的線程。
threading.activeCount(): 返回正在運行的線程數量,與len(threading.enumerate())有相同的結果。
threading模塊提供的類:
Thread, Lock, Rlock, Condition, [Bounded]Semaphore, Event, Timer, local.
Thread是線程類,與Java類似,有兩種使用方法,直接傳入要運行的方法或從Thread繼承并覆蓋run():
# encoding: UTF-8
import threading
# 方法1:將要執(zhí)行的方法作為參數傳給Thread的構造方法
def func():
print 'func() passed to Thread'
t = threading.Thread(target=func)
t.start()
# 方法2:從Thread繼承,并重寫run()
class MyThread(threading.Thread):
def run(self):
print 'MyThread extended from Thread'
t = MyThread()
t.start()
構造方法:
Thread(group=None, target=None, name=None, args=(), kwargs={})
group: 線程組,目前還沒有實現,庫引用中提示必須是None;
target: 要執(zhí)行的方法;
name: 線程名;
args/kwargs: 要傳入方法的參數。
實例方法:
isAlive(): 返回線程是否在運行。正在運行指啟動后、終止前。
get/setName(name): 獲取/設置線程名。
is/setDaemon(bool): 獲取/設置是否守護線程。初始值從創(chuàng)建該線程的線程繼承。當沒有非守護線程仍在運行時,程序將終止。
start(): 啟動線程。
join([timeout]): 阻塞當前上下文環(huán)境的線程,直到調用此方法的線程終止或到達指定的timeout(可選參數)。
一個使用join()的例子:
# encoding: UTF-8 import threading import time def context(tJoin): print 'in threadContext.' tJoin.start() # 將阻塞tContext直到threadJoin終止。 tJoin.join() # tJoin終止后繼續(xù)執(zhí)行。 print 'out threadContext.' def join(): print 'in threadJoin.' time.sleep(1) print 'out threadJoin.' tJoin = threading.Thread(target=join) tContext = threading.Thread(target=context, args=(tJoin,)) tContext.start()
運行結果:
in threadContext.
in threadJoin.
out threadJoin.
out threadContext.
希望本文所述對大家的Python程序設計有所幫助。
- 對python多線程中互斥鎖Threading.Lock的簡單應用詳解
- Python多線程threading和multiprocessing模塊實例解析
- Python基于ThreadingTCPServer創(chuàng)建多線程代理的方法示例
- Python中Threading用法詳解
- python使用threading獲取線程函數返回值的實現方法
- Python 多線程Threading初學教程
- Python用threading實現多線程詳解
- 在Python中通過threading模塊定義和調用線程的方法
- Python中線程編程之threading模塊的使用詳解
- 舉例詳解Python中threading模塊的幾個常用方法
- Python中threading模塊join函數用法實例分析
- python threading模塊操作多線程介紹
- Python THREADING模塊中的JOIN()方法深入理解
- python多線程threading.Lock鎖用法實例
- python基于queue和threading實現多線程下載實例
- 對python:threading.Thread類的使用方法詳解
相關文章
詳解Python執(zhí)行py文件是否需要可執(zhí)行權限
這篇文章主要通過幾個案例為大家詳細介紹一下在Python中執(zhí)行py文件是否需要可執(zhí)行權限,文中的示例代碼講解詳細,對我們學習Python有一定幫助,需要的可以了解一下2023-03-03

