threading基于Java的線程模型設(shè)計(jì)。鎖(Lock)和條件變量(Condition)在Java中是對(duì)象的基本行為(每一個(gè)對(duì)象都自帶了鎖和條件變量),而在Python中則是獨(dú)立的對(duì)象。Python Thread提供了Java Thread的行為的子集;沒有優(yōu)先級(jí)、線程組,線程也不能被停止、暫停、恢復(fù)、中斷。Java Thread中的部分被Python實(shí)現(xiàn)了的靜態(tài)方法在threading中以模塊方法的形式提供。
threading 模塊提供的常用方法:
threading.currentThread(): 返回當(dāng)前的線程變量。
threading.enumerate(): 返回一個(gè)包含正在運(yùn)行的線程的list。正在運(yùn)行指線程啟動(dòng)后、結(jié)束前,不包括啟動(dòng)前和終止后的線程。
threading.activeCount(): 返回正在運(yùn)行的線程數(shù)量,與len(threading.enumerate())有相同的結(jié)果。
threading模塊提供的類:
Thread, Lock, Rlock, Condition, [Bounded]Semaphore, Event, Timer, local.
Thread是線程類,與Java類似,有兩種使用方法,直接傳入要運(yùn)行的方法或從Thread繼承并覆蓋run():
# encoding: UTF-8 import threading # 方法1:將要執(zhí)行的方法作為參數(shù)傳給Thread的構(gòu)造方法 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()
構(gòu)造方法:
Thread(group=None, target=None, name=None, args=(), kwargs={})
group: 線程組,目前還沒有實(shí)現(xiàn),庫引用中提示必須是None;
target: 要執(zhí)行的方法;
name: 線程名;
args/kwargs: 要傳入方法的參數(shù)。
實(shí)例方法:
isAlive(): 返回線程是否在運(yùn)行。正在運(yùn)行指啟動(dòng)后、終止前。
get/setName(name): 獲取/設(shè)置線程名。
is/setDaemon(bool): 獲取/設(shè)置是否守護(hù)線程。初始值從創(chuàng)建該線程的線程繼承。當(dāng)沒有非守護(hù)線程仍在運(yùn)行時(shí),程序?qū)⒔K止。
start(): 啟動(dòng)線程。
join([timeout]): 阻塞當(dāng)前上下文環(huán)境的線程,直到調(diào)用此方法的線程終止或到達(dá)指定的timeout(可選參數(shù))。
一個(gè)使用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()
運(yùn)行結(jié)果:
in threadContext.
in threadJoin.
out threadJoin.
out threadContext.
希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com