Python3 線程中常用的兩個模塊為:
_thread
threading(推薦使用)
thread 模塊已被廢棄搬俊。用戶可以使用 threading 模塊代替。所以黔宛,在 Python3 中不能再使用"thread" 模塊竞思。為了兼容性娘荡,Python3 將 thread 重命名為 "_thread"。
函數(shù)時調(diào)用:
最簡單的讀線程案例:
#threading模塊創(chuàng)建線程實例
#步驟:1.用Thread類創(chuàng)建一個實例 2.實例化后調(diào)用start方法啟動線程
from threading import Thread
#線程函數(shù)
def threadDemo(msg):
? ? print(msg)
if __name__ == '__main__':
? ? #實例化線程類,target參數(shù)為線程執(zhí)行的函數(shù)魁袜,args參數(shù)為線程函數(shù)的參數(shù)
? ? thread1 = Thread(target=threadDemo,args=('this is a thread demo',))
? ? thread1.start()
輸出:this is a thread demo
繼承式調(diào)用
#步驟:1.繼承Thread類創(chuàng)建一個新的子類 2.實例化后調(diào)用start方法啟動線程
#線程函數(shù)
def threadDemo(msg):
? ? print(msg)
class MyThread(Thread):
? ? def __init__(self,msg):
? ? ? ? super(MyThread,self).__init__()
? ? ? ? self.msg = msg
? ? def run(self):
? ? ? ? threadDemo(self.msg)
if __name__ == '__main__':
? ? t1 = MyThread('thread t1')
? ? t2 = MyThread('thread t2')
? ? t1.start()
? ? t2.start()
? ? t1.join()
? ? t2.join()
輸出:thread t1
? ? ? ? ?? thread t2
線程同步
線程在運行時是相互獨立的瞄沙,線程與線程間互不影響
def print_time(threadName,count,delay):
? ? while count:
? ? ? ? time.sleep(delay)
? ? ? ? print("%s: %s" % (threadName, time.ctime(time.time())))
? ? ? ? count -= 1
class MyThread(Thread):
? ? def __init__(self,name,count):
? ? ? ? super(MyThread,self).__init__()
? ? ? ? self.name = name
? ? ? ? self.count = count
? ? def run(self):
? ? ? ? print('線程開始'+self.name)
? ? ? ? print_time(self.name,self.count,2)
? ? ? ? print('線程結(jié)束'+self.name)
if __name__ == '__main__':
? ? th1 = MyThread('th1',5)
? ? th2 = MyThread('th2',5)
? ? th1.start()
? ? th2.start()
? ? th1.join()
? ? th2.join()
? ? print('--主線程結(jié)束--')
輸出結(jié)果:
線程開始th1
線程開始th2
th1: Tue Dec 31 10:25:30 2019
th2: Tue Dec 31 10:25:30 2019
th1: Tue Dec 31 10:25:32 2019
th2: Tue Dec 31 10:25:32 2019
th1: Tue Dec 31 10:25:34 2019
th2: Tue Dec 31 10:25:34 2019
th1: Tue Dec 31 10:25:36 2019
th2: Tue Dec 31 10:25:36 2019
th1: Tue Dec 31 10:25:38 2019
線程結(jié)束th1
th2: Tue Dec 31 10:25:38 2019
線程結(jié)束th2
--主線程結(jié)束--