Java多執行緒實現非同步呼叫
阿新 • • 發佈:2019-01-10
在JAVA平臺,實現非同步呼叫的角色有如下三個角色:呼叫者 提貨單 真實資料
一個呼叫者在呼叫耗時操作,不能立即返回資料時,先返回一個提貨單.然後在過一斷時間後憑提貨單來獲取真正的資料.
去蛋糕店買蛋糕,不需要等蛋糕做出來(假設現做要很長時間),只需要領個提貨單就可以了(去幹別的事情),等到蛋糕做好了,再拿提貨單取蛋糕就可以了。
publicclass Main {
- publicstaticvoid main(String[] args) {
- System.out.println("main BEGIN");
- Host host = new Host();
- Data data1 = host.request(10, 'A');
- Data data2 = host.request(20, 'B');
- Data data3 = host.request(30, 'C');
-
System.out.println(
- try {
- Thread.sleep(200);
- } catch (InterruptedException e) {
- }
- System.out.println("main otherJob END");
- System.out.println("data1 = " + data1.getContent());
-
System.out.println("data2 = " + data2.getContent());
- System.out.println("data3 = " + data3.getContent());
- System.out.println("main END");
- }
- }
下面來看一下,顧客定蛋糕後,蛋糕店做了什麼:
- publicclass Host {
- public Data request(finalint count, finalchar c) {
- System.out.println("request(" + count + ", " + c + ") BEGIN");
- // (1) 建立FutureData的實體
- final FutureData future = new FutureData();
- // (2) 為了建立RealData的實體,啟動新的執行緒
- new Thread() {
- publicvoid run() {
- //在匿名內部類中使用count、future、c。
- RealData realdata = new RealData(count, c);
- future.setRealData(realdata);
- }
- }.start();
- System.out.println("request(" + count + ", " + c + ") END");
- // (3) 取回FutureData實體,作為傳回值
- return future;
- }
- }
下面來看看蛋糕師傅是怎麼做蛋糕的:
建立一個字串,包含count個c字元,為了表現出犯法需要花費一些時間,使用了sleep。
publicclass RealData implements Data {- privatefinal String content;
- public RealData(int count, char c) {
- System.out.println("making RealData(" + count + ", " + c + ") BEGIN");
- char[] buffer = newchar[count];
- for (int i = 0; i < count; i++) {
- buffer[i] = c;
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- }
- }
- System.out.println("making RealData(" + count + ", " + c + ") END");
- this.content = new String(buffer);
- }
- public String getContent() {
- return content;
- }
- }
現在來看看“提貨單”future是怎麼與蛋糕"content"對應的:
publicclass FutureData implements Data {- private RealData realdata = null;
- privateboolean ready = false;
- publicsynchronizedvoid setRealData(RealData realdata) {
- if (ready) {
- return; // 防止setRealData被呼叫兩次以上。
- }
- this.realdata = realdata;
- this.ready = true;
- notifyAll();
- }
- publicsynchronized String getContent() {
- while (!ready) {
- try {
- wait();
- } catch (InterruptedException e) {
- }
- }
- return realdata.getContent();
- }
- }
顧客做完自己的事情後,會拿著自己的“提貨單”來取蛋糕:
System.out.println("data1 = " + data1.getContent());
這時候如果蛋糕沒做好,就只好等了:
while (!ready) {- try {
- wait();
- } catch (InterruptedException e) {
- }
- //等做好後才能取到
- return realdata.getContent();
程式分析
對於每個請求,host都會生成一個執行緒,這個執行緒負責生成顧客需要的“蛋糕”。在等待一段時間以後,如果蛋糕還沒有做好,顧客還必須等待。直到“蛋糕被做好”,也就是
future.setRealData(realdata); 執行以後,顧客才能拿走蛋糕。
每個執行緒只是專門負責製作特定顧客所需要的“蛋糕”。也就是顧客A對應著蛋糕師傅A,顧客B對應著蛋糕師傅B。即使顧客B的蛋糕被先做好了,顧客A也只能等待蛋糕師傅A把蛋糕做好。換句話說,顧客之間沒有競爭關係。
類FutureData的兩個方法被設定為synchronized,實際上蛋糕師傅A與顧客A之間的互斥關係,也就是顧客A必須等待蛋糕師傅A把蛋糕做好後,才能拿走,而與蛋糕師傅B是否做好了蛋糕沒有關係。