新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷(xiāo)解決方案
創(chuàng)新互聯(lián)Python教程:python多線程的實(shí)現(xiàn)方式
本文教程操作環(huán)境:windows7系統(tǒng)、Python 3.9.1,DELL G3電腦。

方法一:創(chuàng)建threading.Thread對(duì)象
import threading
def tstart(arg):
print(f"{arg}running" )
if __name__ == '__main__':
t1 = threading.Thread(target=tstart, args=('This is thread 1',))
t2 = threading.Thread(target=tstart, args=('This is thread 2',))
t1.start()
t2.start()
print("This is main function")方法二:繼承于threading.Thread,重寫(xiě)方法run()
import threading
import time
# 重寫(xiě)一個(gè)類(lèi),繼承于threading.Thread
class MyThread(threading.Thread):
def __init__(self, jobName):
super(MyThread, self).__init__()
self.jobName = jobName
# 重寫(xiě)run方法, 實(shí)現(xiàn)多線程, 因?yàn)閟tart方法執(zhí)行時(shí), 調(diào)用的是run方法;
# run方法里面編寫(xiě)的內(nèi)容就是你要執(zhí)行的任務(wù);
def run(self):
print("這是一個(gè)需要執(zhí)行的任務(wù)%s。" %(self.jobName))
print("當(dāng)前線程的個(gè)數(shù):", threading.active_count() )
time.sleep(1)
print("當(dāng)前線程的信息:", threading.current_thread())
if __name__ == '__main__':
t1 = MyThread("name1")
t2 = MyThread("name2")
t1.start()
t2.start()
t1.join()
t2.join()
print("程序執(zhí)行結(jié)束.....")以上就是python多線程的兩種實(shí)現(xiàn)方法,大家可以根據(jù)具體情況選擇不同的實(shí)現(xiàn)方法,希望能對(duì)你有所幫助哦~
當(dāng)前文章:創(chuàng)新互聯(lián)Python教程:python多線程的實(shí)現(xiàn)方式
當(dāng)前網(wǎng)址:http://www.5511xx.com/article/ccdisjg.html


咨詢
建站咨詢
