一些經常使用函數:多線程
start():開始線程活動。 threading.Lock():建立鎖 acquire():線程加鎖 release():釋放鎖 threading.activeCount():返回當前」進程」裏面」線程」的個數(包含主進程) threading.enumerate() :返回當前運行中的Thread對象列表 threading.setDaemon():參數設置爲True的話會將線程聲明爲守護線程,必須在start() 方法以前設置,不設置爲守護線程程序會被無限掛起。 join()方法來使得子進程運行結束後再執行父進程
我的比較喜歡建立線程類來實現多線程 來個簡單的例子,開2個線程,打印時間,未加鎖狀況函數
# -*- coding: UTF-8 -*- import threading import time class MyThread(threading.Thread): def __init__(self, threadID, name, counter): super(MyThread, self).__init__() self.threadID, self.name, self.counter = threadID, name, counter def run(self): print "進程開始: " + self.name self.run_fun(self.name, self.counter, 3) print "進程退出:" + self.name def run_fun(self, threadName, delay, counter): while counter: time.sleep(delay) print "%s: %s" % (threadName, time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())) counter -= 1 thread1 = MyThread(1, 'thread-1', 1) thread2 = MyThread(2, 'thread-2', 2) thread1.start() thread2.start() print threading.enumerate() print "主進程退出"
結果很明顯,線程1和線程2同時執行ui
加鎖狀況線程
# -*- coding: UTF-8 -*- import threading import time class MyThread(threading.Thread): def __init__(self, threadID, name, counter): super(MyThread, self).__init__() self.threadID, self.name, self.counter = threadID, name, counter def run(self): print "進程開始: " + self.name threadLock.acquire() # 得到鎖 self.run_fun() threadLock.release() # 釋放鎖 print "進程退出:" + self.name def run_fun(self): counter = 3 while counter: time.sleep(self.counter) print "%s: %s" % (self.name, time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())) counter -= 1 threadLock = threading.Lock() thread1 = MyThread(1, 'thread-1', 1) thread2 = MyThread(2, 'thread-2', 2) thread1.start() thread2.start() print threading.enumerate() #顯示運行的線程 print "主進程退出"
結果很明顯,加鎖以後,線程1執行完,線程2纔會執行code