天天看點

python threading超線程使用簡單範例的代碼

在工作過程中中,将内容過程中經常用的内容片段珍藏起來,下面内容段是關于python threading超線程使用簡單範例的内容,希望能對小夥伴們有較大幫助。

# 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()的例子:

# 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.
           

轉載于:https://blog.51cto.com/14137986/2349339