1、数据接口层:
package multithread;
public interface Data2 {
public abstract String getContent();
}
2、真实数据层:
package multithread;
public class RealData implements Data2{
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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(" making realdata("+count+","+c+") end");
this.content = new String(buffer);
}
public String getContent(){
return content;
}
}
3、虚拟数据层(提货单):
package multithread;
/**
* @author Administrator
*提货单
*/
public class FutureData implements Data2{
private RealData realdata = null;
private boolean ready = false;
public synchronized String getContent(){
while(!ready){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return realdata.getContent();
}
public synchronized void setRealData(RealData realdata){
if(ready)
return ;
this.realdata = realdata;
this.ready = true;
notifyAll();
}
}
4、处理数据层:
package multithread;
public class Host2 {
public Data2 request(final int count,final char c){
System.out.println(Thread.currentThread().getName()+" ....");
System.out.println(" request("+count+", "+c+") begin");
final FutureData future = new FutureData();
//System.out.println(future.toString());
new Thread(){
public void run(){
RealData realdata = new RealData(count ,c);
future.setRealData(realdata);
}
}.start();
System.out.println(" request("+count+", "+c+") end");
return future;
}
}
5、测试类:
package multithread;
public class Main5 {
public static void main(String args[]){
System.out.println("main begin");
Host2 host = new Host2();
Data2 data1 = host.request(10, 'A');
Data2 data2 = host.request(20, 'B');
Data2 data3 = host.request(30, 'C');
System.out.println("main otherjob begin");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
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");
}
}