future的簡單實現

2021-08-20 21:10:50 字數 1845 閱讀 6716

一 .入門

public classaimplementscallable

}

@org.junit.test

public voidtest3()throwsexecutionexception, interruptedexception

這樣結果就輸出了

aaa很簡單吧,現在來簡單講解下future的使用。

二. 理解future

future模式是一種非同步獲取結果的方式

public

inte***ce future

feture的使用一般使用執行緒池來獲取值。

現在來簡單梳理一下呼叫邏輯

執行緒池一般都會繼承executorservice,最終會執行到threadpoolexecutor的execute方法,之後利用blockingqueue來獲取值。它裡面用的是condition的await和signal方法。由於物件的await和notify方法和它們類似。那本篇主要使用await和notify來實現future的功能。

三.future **實現

public inte***ceidata
public classrealdataimplementsidatacatch(interruptedexception e) 

data="init finish!"+ name; //賦值

}@override

publicrealdata getresult()

publicstring getdata()

}

public classfuturedataimplementsidata 

system.out.println("值設定成功!");

}@override

publicrealdata getresult()

}catch(interruptedexception e)

returnrealdata;}}

public classfutureclint 

}).start();

returnfuturedata; //這裡是非同步返回的}}

@org.junit.test

public voidfuturedatatest()throwsinterruptedexception

結果

get data     //這裡結果輸出之後應該會等2秒,

值設定成功!

result:init finish!result  //非同步通知,這裡的值會輸出

四.總結

實現個簡單的Future

直接貼demo 1.第一種使用喚醒等待執行緒方式 public inte ce gycallable public class gyfeature implements runnable override public void run catch throwable throwable final...

簡單的Future模式及其實現

future模式是乙個多執行緒的設計模式,以下乙個簡單的實現例子。實現的原理有點類似訂蛋糕,你去商店定做蛋糕時,並不能直接拿到蛋糕,而是拿到購物小票之類的,你需要等蛋糕製作完成後,再來取。在這期間你可以去做其他的事情,而不必在蛋糕店等待蛋糕的製作。這和單獨開乙個執行緒沒有什麼區別,具體有什麼好處我目...

Python的未來 future模組

簡單介紹一下python未來將會支援的一些語言特點 雖然ibm的 上也有介紹.但是太凌亂了.而且中翻譯過後,的格式想狗屎一樣.下面簡單介紹一下這些特點 nested scopes 改變名空間的搜尋過程 generators 使用生成器.能夠產生能儲存當前狀態的函式.division 精確的除法 ab...