多執行緒處理返回值

2021-09-26 23:32:35 字數 927 閱讀 2433

說了很多廢話,只是希望自己警醒,希望認同上述觀點的人同樣能感受到那些每天看凌晨三點太陽的人的壓力,其他不認同的人大概可以跳過直接看下面的內容。本文要寫的內容是關於執行緒,工作中有些寫業務**的開發這塊用得比較少,但是面試時面試官總喜歡問多執行緒相關問題,例如下面這些:

1)什麼是執行緒

2)怎麼樣實現多執行緒

3)有沒有用過執行緒池

4)怎麼樣實現乙個執行緒池

5)不要執行緒池可不可以

這些問題大家可以思考下,本文不對上述問題進行解答。大家都知道new乙個執行緒或者實現ruannable介面,排程這些執行緒是沒有返回值的,如果我們需要執行緒任務處理完畢會返回乙個成功與否的標誌,那麼可以採用下面的方式

public class task implements callable

/*** computes a result, or throws an exception if unable to do so.

** @return computed result

* @throws exception if unable to compute a result

*/@override

public string call() throws exception

}

執行緒類沒有實現runnable介面,而是實現callable介面的call方法。

public class test 

for(futurefuture : list)

}}

建立了乙個快取執行緒池(執行緒池的執行緒數會動態伸縮),將執行緒任務放到執行緒池中執行,結果被儲存到future泛型的list中。最後列印出所有執行緒任務的結果。

大家可以思考下執行緒池執行任務返回結果是同步還是非同步的,這種同步或者非同步的效果又是通過什麼方式實現的,我們拿到的結果是否真實。

多執行緒返回值

多執行緒返回值,避免阻塞提高效率。public class callabledemo1implements callable system.out.println callabledemo1 end system.out.println thread1test.ct thread1test.ct.c...

Python多執行緒獲取返回值

在使用多執行緒的時候難免想要獲取其操作完的返回值進行其他操作,下面的方法以作參考 一,首先重寫threading類,使其滿足呼叫特定的方法獲取其返回值 import threading class mythread threading.thread 重寫多執行緒,使其能夠返回值 def init s...

Python多執行緒獲取返回值

在使用多執行緒的時候難免想要獲取其操作完的返回值進行其他操作,下面的方法以作參考 一,首先重寫threading類,使其滿足呼叫特定的方法獲取其返回值 import threadingclass mythread threading.thread 重寫多執行緒,使其能夠返回值 def init se...