-
public static void main(String[] args) { -
System.out.println("main BEGIN"); -
Host host = new Host(); -
FutureData data1 = host.request(10, 'A'); -
FutureData data2 = host.request(20, 'B'); -
FutureData data3 = host.request(30, 'C'); -
-
System.out.println("main otherJob BEGIN"); -
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"); -
} - }
下面来看一下,顾客定蛋糕后,蛋糕店做了什么:
- public
class Host { -
public FutureData request(final int count, final char c) { -
System.out.println("request(" + count + ", " + c + ") BEGIN"); -
-
// (1) 建立FutureData的实体 -
final FutureData future = new FutureData(); -
-
// (2) 为了建立RealData的实体,启动新的线程 -
new Thread() { -
public void 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。
-
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(1000); -
} catch (InterruptedException e) { -
} -
} -
System.out.println("making RealData(" + count + ", " + c + ") END"); -
this.content = new String(buffer); -
} -
public String getContent() { -
return content; -
} - }
-
private RealData realdata = null; -
private boolean ready = false; -
-
public synchronized void setRealData(RealData realdata) { -
if (ready) { -
return; // 防止setRealData被调用两次以上。 -
} -
this.realdata = realdata; -
this.ready = true; -
notifyAll(); -
} -
public synchronized String getContent() { -
while (!ready) { -
try { -
wait(); -
} catch (InterruptedException e) { -
} -
} -
return realdata.getContent(); -
} - }
System.out.println("data1
-
try { -
wait(); -
} catch (InterruptedException e) { -
} - //等做好后才能取到
- return
realdata.getContent();
future.setRealData(realdata);