獲取執行緒的執行結果

2021-10-04 16:07:32 字數 3446 閱讀 8071

最本質的區別在於,runnable沒有返回結果,callable會有乙個返回結果,返回結果是泛型,可以自己定義。舉例子說明:

上述例子中可以看到,callable可以定義乙個返回結果,通過futuretask的get方法可以獲得執行緒執行後的結果(阻塞等待結果)。

原始碼檢視:

/**

* allocates a new object. this constructor has the same

* effect as

* , where is a newly generated

* name. automatically generated names are of the form

* n, where n is an integer.

** @param target

* the object whose method is invoked when this thread

* is started. if , this classes method does

* nothing.

*/public thread(runnable target)

public class futuretaskimplements runnablefuture
/**

* a that is . successful execution of

* the method causes completion of the

* and allows access to its results.

* @see futuretask

* @see executor

* @since 1.6

* @author doug lea

* @param the result type returned by this future's method

*/public inte***ce runnablefutureextends runnable, future

上面的**看到了:最終futuretask也是實現了runnable。

futuretask的get可以阻塞等待結果,那麼在寫之前思考下,需要哪些步驟?

步驟如下:

1:需要去重寫繼承的runnable介面的run方法;

2:需要乙個callable變數,用來執行call()方法;

3:需要乙個泛型的變數,用來存放結果;

4:還需要乙個佇列,用來存放那些阻塞還未返回結果的執行緒;

5:需要乙個標誌,判斷執行緒是否執行完,可以返回結果;

6:最後,需要乙個獲取結果的方法。

**實現如下,有注釋可以方便檢視:

public class threadfuturetaskimplements runnable 

//實現runnable的run方法

@override

public void run() catch (exception e) finally

//把佇列中阻塞的執行緒,喚醒,否則獲取不到結果

while (true)

//喚醒掛起的執行緒

locksupport.unpark(thread);}}

//獲取結果的方法

public t get()

//讓執行緒掛起

while (!isending)

//返回結果

return result;}}

然後再去上面的runnable和callable區別的測試類裡測試一下:

public static void main(string args) throws executionexception, interruptedexception
返回結果如下:

可以看到,返回結果和futuretask一樣,這樣就實現了futuretask的功能。

countdownlatch是乙個同步工具類,它是讓乙個或者多個執行緒等待,直到其他執行緒執行完再執行;countdownlatch是通過倒計數器來實現的,它的初始值就是執行緒的數量,每當乙個執行緒執行完畢,計數器就減一,直到減到0,輸出所有執行緒執行的結果,等待的執行緒就可以恢復繼續執行。

public static atomiclong num = new atomiclong(0);

public static void main(string args) throws interruptedexception

//計數器減1

latch.countdown();

}).start();

}//開啟開關

latch.await();

system.out.println(num.get());

}

semaphore是乙個計數訊號量,可以控制訪問資源的執行緒數量,也就是說,它是乙個可以控制併發的共享鎖,也就是限流。

public static void main(string args)  catch (interruptedexception e) 

test("222");

//執行完釋放通道

semaphore.release();

}).start();}}

public static void test(string name)

cyclicbarrier迴圈柵欄,可以迴圈利用的屏障,它的作用就是讓執行緒都等待完成後才會再去執行。

比如:去遊樂園做摩天輪,假設只能上齊四個人才允許啟動,那麼再沒有上齊之前,其他人就在等待。

public static void main(string args)  catch (interruptedexception | brokenbarrierexception e) 

}).start();}}

好了,到此,本篇文章就結束了。 

獲取子執行緒的執行結果

public class thread implements runnable private static class task implements callable public static void main string args throws executionexception,in...

Future獲取子執行緒的執行結果

runnable的缺陷 functionalinte ce public inte ce runnable callable介面類似於runnable,被其他執行緒執行的任務 實現call方法,有返回值 functionalinte ce public inte ce callable callab...

如何獲取子執行緒的執行結果

對於執行緒的管理,我們不僅可以通過執行緒池進行管理,我們還可以通過future和callable進行管理。runnable介面無法返回乙個值返回。runnable介面原始碼 functionalinte ce public inte ce runnable runnable介面不能丟擲checked...