在JAVA平台
System
Host host = new Host();
Data data
Data data
Data data
System
try {
Thread
} catch (InterruptedException e) {
}
System
System
System
System
System
}
}
這裡的main類就相當於
下面來看一下
public class Host {
public Data request(final int count
System
// (
final FutureData future = new FutureData();
// (
new Thread() {
public void run() {
//在匿名內部類中使用count
RealData realdata = new RealData(count
future
}
}
System
// (
return future;
}
}
host(
下面來看看蛋糕師傅是怎麼做蛋糕的
建立一個字符串
public class RealData implements Data { private final String content;
public RealData(int count
System
char[] buffer = new char[count];
for (int i =
buffer[i] = c;
try {
Thread
} catch (InterruptedException e) {
}
}
System
ntent = 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; // 防止setRealData被調用兩次以上
}
this
this
notifyAll();
}
public synchronized String getContent() {
while (!ready) {
try {
wait();
} catch (InterruptedException e) {
}
}
return realdata
}
}
顧客做完自己的事情後
System
這時候如果蛋糕沒做好
while (!ready) { try {
wait();
} catch (InterruptedException e) {
}
//等做好後才能取到
return realdata
程序分析
對於每個請求
future
每個線程只是專門負責制作特定顧客所需要的
類FutureData的兩個方法被設置為synchronized
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27425.html