轉載自http://eyesmore.iteye.com/blog/243648javascript
在多線程交互的中2,常常有一個線程須要獲得另個一線程的計算結果,咱們經常使用的是Future異步模式來加以解決。
Future顧名思意,有點像期貨市場的「期權」,是「對將來的一種憑證」,例如當咱們買了某個房地產開發商的期房,交錢以後,開發商會給咱們一個憑證(期權),這個憑證告訴咱們等明年某個時候拿這個憑證就能夠拿到咱們所須要的房子,可是如今房子還沒建好。市場上之因此有「期貨」,也正因爲有這種需求,纔有這種供給。java
這種應用在GUI上用的比較多,在設計模式中通常稱爲「虛擬代理模式」。設計模式
例如:如今有個這樣的需求,Client向Server提交一個Request(int count,char c),但願獲取一個由count個字符c構造出來的字符串。好比發送Request(10,'K'),那麼反饋字符串「KKKKKKKKKK」,可是咱們假設這個生成字符串的過程很費時間。多線程
因而,爲了獲取比較好的交互性,咱們的Server收到請求後,先構造一個FutureData,並把這個所謂的「期權(將來憑證)」反饋給Client;於此同時,經過另外一個併發線程去構造一個真正的字符串RealData,並在構造完畢後,RealData給FutureData報告一個消息,說數據(期房)已經準備好了,此時Client能夠經過期權拿到期房,可是假如咱們的Client比較着急,還沒等房子假好的時,就想要房子,怎麼辦呢?這個時候咱們能夠阻塞Client所在的線程,讓Client等待,直到最後RealData通知FutureData說房子好了,才返回。併發
這裏的要點:異步
(1)Server先給Client一個「期權」,同時開一個線程去幹活建房子(將來的「現房」);ide
(2)當「現房」RealData準備好了的時候,如何告訴FutureData說已經準備好了。(本處採用「回調過程」(借用觀察者模式,來實現回調))this
(3)若是客戶比較着急,現房還沒準備好的時候,就要取房,怎麼辦? 本處採用「阻塞」。url
Data(公共數據接口)spa
- package com.umpay.future;
-
- public interface Data {
- public abstract String getContent();
- }
package com.umpay.future;
public interface Data {
public abstract String getContent();
}
FutureData(期權)
- package com.umpay.future.extend;
-
- import java.util.Observable;
- import java.util.Observer;
-
- import com.umpay.future.Data;
-
- public class FutureData2 implements Data,Observer {
-
-
-
-
-
-
- private volatile RealData2 realData2 = null;
-
-
-
- public boolean isFinished() {
- return realData2 != null;
- }
-
-
-
-
-
- public String getContent() {
- synchronized (mutex) {
- while(!isFinished()) {
- try {
- mutex.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- return realData2.getContent();
- }
- }
-
-
-
-
-
-
-
-
- public void update(Observable realData, Object event) {
- System.out.println("通知...."+event);
- if(!(realData instanceof RealData2)) {
- throw new IllegalArgumentException("主題的數據類型必須是RealData2");
- }
- if(!(event instanceof String)) {
- throw new IllegalArgumentException("事件的數據類型必須是String");
- }
- synchronized (mutex) {
- if(isFinished()) {
- mutex.notifyAll();
- return;
- }
- if("Finished".equals(event)) {
- realData2 = (RealData2)realData;
- mutex.notifyAll();
- }
- }
- }
-
- private Object mutex = new Object();
- }
package com.umpay.future.extend;
import java.util.Observable;
import java.util.Observer;
import com.umpay.future.Data;
public class FutureData2 implements Data,Observer {
/**
* 存放真實數據,而且標誌真正的數據是否已經準備完畢
* 被多線程享受
* 若是realData2==null,表示數據還準備好
* */
private volatile RealData2 realData2 = null;
/**
* 查看真正的數據是否準備完畢
* */
public boolean isFinished() {
return realData2 != null;
}
/**
* 若是數據已經準備好,則返回真正的數據;
* 不然,阻塞調用線程,直到數據準備完畢後,才返回真實數據;
* */
public String getContent() {
synchronized (mutex) {
while(!isFinished()) {//只要數據沒有準備完畢,就阻塞調用線程
try {
mutex.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return realData2.getContent();
}
}
/**
* 當 RealData2 準備完數據後,RealData2 應該通知 FutureData2 數據準備完畢。
* 並在輸入參數 realData 傳入真實數據,在參數 event 傳入事件(好比數據如期準備好了,或出了什麼異常)
*
* @param realData 真實的數據
* @param event 事件類型
* */
public void update(Observable realData, Object event) {
System.out.println("通知...."+event);
if(!(realData instanceof RealData2)) {
throw new IllegalArgumentException("主題的數據類型必須是RealData2");
}
if(!(event instanceof String)) {
throw new IllegalArgumentException("事件的數據類型必須是String");
}
synchronized (mutex) {
if(isFinished()) {
mutex.notifyAll();
return;//若是數據已經準備好了,直接返回.
}
if("Finished".equals(event)) {
realData2 = (RealData2)realData;//數據準備好了的時候,即可以通知數據準備好了
mutex.notifyAll();//喚醒被阻塞的線程
}
}
}
private Object mutex = new Object();
}
RealData(實際數據)
- package com.umpay.future.extend;
-
- import java.util.Observable;
-
- import com.umpay.future.Data;
-
- public class RealData2 extends Observable implements Data {
-
- private String content;
-
- public RealData2() {
-
- }
-
- public void createRealData2(int count, char c) {
- System.out.println(" making RealData(" + count + ", " + c
- + ") BEGIN");
- char[] buffer = new char[count];
- for (int i = 0; i < count; i++) {
- buffer[i] = c;
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- }
- }
- System.out.println(" making RealData(" + count + ", " + c
- + ") END");
- this.content = new String(buffer);
-
-
- setChanged();
- notifyObservers("Finished");
- }
-
-
- public String getContent() {
- return content;
- }
- }
package com.umpay.future.extend;
import java.util.Observable;
import com.umpay.future.Data;
public class RealData2 extends Observable implements Data {
private String content;
public RealData2() {
}
public void createRealData2(int count, char c) {
System.out.println(" making RealData(" + count + ", " + c
+ ") BEGIN");
char[] buffer = new char[count];
for (int i = 0; i < count; i++) {
buffer[i] = c;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
System.out.println(" making RealData(" + count + ", " + c
+ ") END");
this.content = new String(buffer);
//真實數據準備完畢了,通知FutureData2說數據已經準備好了.
setChanged();//必須先設置本對象的狀態發生了變化,而且通知全部的觀察者
notifyObservers("Finished");
}
public String getContent() {
return content;
}
}
服務端代碼:
- package com.umpay.future.extend;
-
- import com.umpay.future.Data;
-
- public class HostServer2 {
-
- public Data request(final int count, final char c) {
- System.out.println(" request(" + count + ", " + c + ") BEGIN");
-
-
- final FutureData2 future2 = new FutureData2();
-
-
- new Thread() {
- public void run() {
- RealData2 realdata2 = new RealData2();
- realdata2.addObserver(future2);
- realdata2.createRealData2(count, c);
- }
- }.start();
-
- System.out.println(" request(" + count + ", " + c + ") END");
-
-
- return future2;
- }
-
- }
package com.umpay.future.extend;
import com.umpay.future.Data;
public class HostServer2 {
public Data request(final int count, final char c) {
System.out.println(" request(" + count + ", " + c + ") BEGIN");
// (1) 創建FutureData的實體
final FutureData2 future2 = new FutureData2();
// (2) 爲了創建RealData的實體,啓動新的線程
new Thread() {
public void run() {
RealData2 realdata2 = new RealData2();
realdata2.addObserver(future2);//以便當RealData2把數據準備完畢後,經過該回調口子,通知FutureData2表示數據已經貯備好了
realdata2.createRealData2(count, c);
}
}.start();
System.out.println(" request(" + count + ", " + c + ") END");
// (3) 取回FutureData實體,做爲傳回值
return future2;
}
}
客戶端代碼:
- package com.umpay.future;
-
- import com.umpay.future.extend.HostServer2;
-
- public class MainClient {
- public static void main(String[] args) {
-
- testHostServer2();
- }
-
- static void testHostServer() {
- System.out.println("main BEGIN");
- HostServer hostServer = new HostServer();
- Data data1 = hostServer.request(10, 'A');
- Data data2 = hostServer.request(20, 'B');
- Data data3 = hostServer.request(30, 'C');
-
- System.out.println("main otherJob BEGIN");
-
-
-
-
- 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");
-
- }
-
- static void testHostServer2() {
- System.out.println("main BEGIN");
- HostServer2 hostServer2 = new HostServer2();
- Data data1 = hostServer2.request(10, 'A');
- Data data2 = hostServer2.request(20, 'B');
- Data data3 = hostServer2.request(30, 'C');
-
- System.out.println("main otherJob BEGIN");
-
-
-
-
- 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");
-
- }
- }
package com.umpay.future;
import com.umpay.future.extend.HostServer2;
public class MainClient {
public static void main(String[] args) {
// testHostServer();
testHostServer2();
}
static void testHostServer() {
System.out.println("main BEGIN");
HostServer hostServer = new HostServer();
Data data1 = hostServer.request(10, 'A');
Data data2 = hostServer.request(20, 'B');
Data data3 = hostServer.request(30, 'C');
System.out.println("main otherJob BEGIN");
// try {
// Thread.sleep(2000);
// } 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");
}
static void testHostServer2() {
System.out.println("main BEGIN");
HostServer2 hostServer2 = new HostServer2();
Data data1 = hostServer2.request(10, 'A');
Data data2 = hostServer2.request(20, 'B');
Data data3 = hostServer2.request(30, 'C');
System.out.println("main otherJob BEGIN");
// try {
// Thread.sleep(2000);
// } 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");
}
}