如何進行多執行緒程式設計

2022-10-11 01:42:09 字數 2089 閱讀 3871

#對於io操作來說,多執行緒比較好。

#1.通過threading例項化乙個物件

import time

def get_detail_html(url):

print('get detail html')

time.sleep(2) 

print('get detail html end')

def get_detail_url(url):

print("get detail url started")

time.sleep(2)

print('get detail url end')

if __name__ == "__main__":

args傳遞引數進去給函式

thread1 = threading.thread(target=get_detail_html,args=("",))

thread2 = threading.thread(target=get_detail_html,args=("",))

start_time  = time.time()

呼叫start()方法開啟執行緒

thread1.start()

thread2.start()

#需求2:子執行緒執行完,才執行主線程

開啟join()執行緒執行完,才能執行主線程

thread1.join()

thread2.join()

print(''last time:{}''.format(time.time-start_time)) 

從上面的**執行中,我們可以看出主線程執行完,程式並沒有退出,程序沒有**資源,而是等其他執行緒執行完,才**。

現在我有個需求,就是主線程執行完,子執行緒kill掉,直接退出

(只要在呼叫start()方法開啟執行緒之前,設定成守護執行緒就行了,具體該怎麼操作,

#開啟守護執行緒(多執行緒中的守護執行緒是等所有的執行緒執行完畢才kill掉)

thread1.setdaemon(true),

thread2.setdaemon(true)

)----------------------守護執行緒和join()方法比較重要----------------------------------------

對於一些簡單的可以用上面的方法,對於一些比較複雜的境況,要下面的方法

class getdetailhtml(threading.thread):

def __init__(self,name):

super().__init__(name=name)

#必須要繼承threading.thread類實現run()方法

def run(self):

print('get detail html')

time.sleep(2) 

print('get detail html end')

class getdetailurl(threading.thread):

def __init__(self,name):

super().__init__(name=name)

def run(self):
print('get detail url')

time.sleep(2) 

print('get detail url end')

if __name__ == "__main__":

thread1 = getdetailhtml("get_detail_html")

thread2 = getdetailurl("get_detail_url")

start_time  = time.time()

呼叫start()方法開啟執行緒

thread1.start()

thread2.start()

#需求2:子執行緒執行完,才執行主線程

開啟join()執行緒執行完,才能執行主線程

thread1.join()

thread2.join()

print(''last time:{}''.format(time.time-start_time)) 

注意:如果使用執行緒池還是使用第一種方案。

C 如何進行多執行緒程式設計

由於多執行緒程式設計非常複雜,這個小例子只能算是乙個入門線的知識點吧 首先建乙個應用程式專案,命名為threadexample,在窗體上放乙個文字框 textbox1 乙個標籤 lblresult 再放兩個按鈕,分別命名為btnstart btnstop。窗體 namespace threadexa...

多執行緒如何進行資訊交換?

void notify 喚醒在此物件監視器上等待的單個執行緒。void notifyall 喚醒在此物件監視器上等待的所有執行緒。void wait 導致當前的執行緒等待,直到其他執行緒呼叫此物件的notify 方法或notifyall 方法。void wait long timeout 導致當前的...

有趣的多執行緒程式設計(3) 執行緒內部是如何進行的

看一下以下兩個例子的執行結果 testthread.cs using system using system.threading public class test thread.join console.writeline final count count static void threadj...