本文實例講述了python中threading超線程用法。分享給大家供大家參考。具體分析如下:
threading基于Java的線程模型設計。鎖(Lock)和條件變量(Condition)在Java中是對象的基本行為(每一個對象都自帶了鎖和條件變量),而在Python中則是獨立的對象。Python Thread提供了Java Thread的行為的子集;沒有優先級、線程組,線程也不能被停止、暫停、恢復、中斷。Java Thread中的部分被Python實現了的靜態方法在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():
1
2
3
4
5
6
7
8
9
10
11
12
13
|
# encoding: UTF-8 import threading # 方法1:將要執行的方法作為參數傳給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: 要執行的方法;
name: 線程名;
args/kwargs: 要傳入方法的參數。
實例方法:
isAlive(): 返回線程是否在運行。正在運行指啟動后、終止前。
get/setName(name): 獲取/設置線程名。
is/setDaemon(bool): 獲取/設置是否守護線程。初始值從創建該線程的線程繼承。當沒有非守護線程仍在運行時,程序將終止。
start(): 啟動線程。
join([timeout]): 阻塞當前上下文環境的線程,直到調用此方法的線程終止或到達指定的timeout(可選參數)。
一個使用join()的例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
# encoding: UTF-8 import threading import time def context(tJoin): print 'in threadContext.' tJoin.start() # 將阻塞tContext直到threadJoin終止。 tJoin.join() # tJoin終止后繼續執行。 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程序設計有所幫助。