Future是未来,预期的意思,Thread-permessage模式是指将任务交给其他线程来做,但是如果想知道处理的结果,就要使用Future模式,它的典型应用时执行一个需要花一些时间的方法,会立即返回一个future提货单,然后调用方可以继续处理自己的业务逻辑,然后需要的时候再查看future是否返回,一直等到future结果已经处理完毕。
thread-pre-message模式发送的请求很像这样 host.request(10,‘A’),只有请求,没有返回值,而future pattern模式发送请求后会马上就要有返回值,类似这样 Data data=host.request(10,'A'),但是这个data并不是程序执行的结果,只是一个提货单,过一段时间后,可以使用data.getContent()来获取真正的运行结果,调用getContent方法时,如果还没处理完毕,就要等待到处理好为止。
public class FutureThreadTest { /** * @param args */ public static void main(String[] args) { System.out.println("main begin."); Host host = new Host(); Data data1 = host.request(30,'A'); Data data2 = host.request(20,'B'); Data data3 = host.request(10,'C'); System.out.println("main other job begin"); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("main other job end"); System.out.println("data1 = " + data1.getContent()); System.out.println("data2 = " + data2.getContent()); System.out.println("data3 = " + data3.getContent()); } } 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() { @Override public void run() { RealData realdata = new RealData(count, c); future.setRealData(realdata); } }.start(); System.out.println("request(" + count + ", " + c + ")end"); return future; } } interface Data{ public abstract String getContent(); } 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; notify(); } @Override public synchronized String getContent() { while(!ready){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } return realdata.getContent(); } } 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) { e.printStackTrace(); } } System.out.println("making realdata(" + count + "," + c + ")end"); this.content = new String(buffer); } @Override public String getContent() { return content; } }