一、定義
Future模式用來(lái)獲取線程的執(zhí)行結(jié)果。在Thread-Per-Message模式中,如果調(diào)用一個(gè)線程異步執(zhí)行任務(wù),沒(méi)有辦法獲取到返回值,就像:
host.request(10,'A');
而Future模式送出請(qǐng)求后,馬上就要獲取返回值,就像:
Data data=host.request(10,'A');
但是上述的返回值并不是程序的執(zhí)行結(jié)果,因?yàn)榫€程是異步的,主線程調(diào)用該該方法時(shí),異步線程可能才剛剛啟動(dòng)。需要一段時(shí)間后像下面這樣獲取執(zhí)行結(jié)果:
data.getContent();
二、模式案例
Data接口/實(shí)現(xiàn):
public interface Data {
public abstract String getContent();
}
public class RealData implements Data {
private final String content;
public RealData(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);
}
public String getContent() {
return content;
}
}
public class FutureData implements Data {
private RealData realdata = null;
private boolean ready = false;
public synchronized void setRealData(RealData realdata) {
if (ready) {
return;
}
this.realdata = realdata;
this.ready = true;
notifyAll();
}
public synchronized String getContent() {
while (!ready) {
try {
wait();
} catch (InterruptedException e) {
}
}
return realdata.getContent();
}
}
Host類:
public class Host {
public Data request(final int count, final char c) {
System.out.println(" request(" + count + ", " + c + ") BEGIN");
final FutureData future = new FutureData();
new Thread() {
public void run() {
RealData realdata = new RealData(count, c);
future.setRealData(realdata);
}
}.start();
System.out.println(" request(" + count + ", " + c + ") END");
return future;
}
}
執(zhí)行:
public class Main {
public static void 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("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");
}
}
三、模式講解
Future模式的角色如下:
- Client(委托人)參與者
Client參與者會(huì)向Host參與者送出請(qǐng)求(request),Client參與者會(huì)馬上得到VirtualData,作為請(qǐng)求結(jié)果的返回值。(案例中的Main類就是Client) - Host參與者
Host參與者接受請(qǐng)求(request),然后創(chuàng)建線程進(jìn)行異步處理。Host參與者會(huì)立即返回Future(以VirturalData的形式)。 - VirtualData(虛擬數(shù)據(jù))參與者
VirtualData是用來(lái)統(tǒng)一代表Future參與者與RealData參與者。(案例中Data接口就是VirtualData參與者) - RealData(實(shí)際數(shù)據(jù))參與者
RealData表示實(shí)際的數(shù)據(jù)。 - Future參與者
Future參與者包含獲取實(shí)際的數(shù)據(jù)和設(shè)置實(shí)際數(shù)據(jù)的方法。Host類會(huì)創(chuàng)建該對(duì)象,當(dāng)異步線程處理完成時(shí),會(huì)調(diào)用Future的設(shè)置數(shù)據(jù)的方法。