Java多執行緒 - Future模式轉換成ListenableFuture模式,以及AsyncRestTemplate的原理
阿新 • • 發佈:2019-01-06
一、AsyncRestTemplate Demo:
spring4.0提供了RestTemplate
的非同步呼叫版本AsyncRestTemplate
,用其進行非同步呼叫的demo如下:
MultiValueMap headers = new LinkedMultiValueMap(){
{
add("Content-Type", "application/json; charset=UTF-8");
}
}
AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate();
HttpEntity<Object> httpEntity = new HttpEntity<Object>(jsonStr, headers);
Listenable<ResponseEntity<String>> future = asyncRestTemplate.postForEntity(url, httpEntity, String.class);
future.addCallback(new ListenableFutureCallback<ResponseEntity<String>>(){
@Override
public void onFailure (Throwable throwable){
System.out.println(throwable.getMessage());
}
@Override
public void onSuccess(ResponseEntity<String> rs){
//System.out.println(rs.getBody());
System.out.println("回撥執行緒:"+Thread.currentThread().getName());
System.out.println(111111);
}
})
//jsonStr是json字串
System.out. println("主執行緒:"+Thread.currentThread().getName());
System.out.println(222222);
二、執行結果:
主執行緒:http-nio-8097-exec-1
222222
回撥執行緒:SimpleAsyncTaskExecutor-1
111111
三、結果分析:
ListenableFuture與Future的共同點:
ListenableFuture
介面繼承自Future
介面,根據文章Java多執行緒 - Future模式,我們很合理的知道,ListenableFuture
模式也會像Future
模式一樣,另起一個執行緒去執行任務,由以上的實驗可知,回撥函式的執行,確實是在不同於主執行緒的另一個執行緒SimpleAsyncTaskExecutor-1
中執行的。
ListenableFuture與Future的不同點:
如果看了這篇文章Java多執行緒 - Future模式,你就會知道主執行緒在等待Future
物件拿到返回值的時候,是會被子執行緒阻塞的,這大大浪費了主執行緒的效能。而ListenableFuture
,支援回撥,主執行緒可以自己做自己的事情,甚至提前結束,等子執行緒完成任務後自然會執行回撥函式中的程式碼。
何為回撥?私以為就是在某個執行緒中,傳入一個自定義函式,等執行緒任務執行完,自然會去呼叫你定義的函式。具體可參考這篇文章回撥函式定義
四、Future模式轉換成ListenableFuture模式
雖然此處是文章正題,但筆者不想多做解釋,可參考該篇文章ListenableFuture in Guava,文章中提到的Executor和ExecutorService的關係可參考這篇文章Java多執行緒學習(8)執行器
參考:
https://blog.csdn.net/lin74love/article/details/81138134
https://www.cnblogs.com/hupengcool/p/3991310.html