java 多執行緒設計模式之future

心鑫發表於2013-11-07
package com.example.design.future;

public interface Data {
public abstract String getContent();
}


package com.example.design.future;

public class FutureData implements Data {
private RealData realdata = null;
private boolean ready = false;
public synchronized void setRealData(RealData realdata) {
    if (ready) {                        
        return;     // balk
    }
    this.realdata = realdata;
    this.ready = true;
    notifyAll();
}
public synchronized String getContent() {
    while (!ready) {
        try {
            wait();
        } catch (InterruptedException e) {
        }
    }
    return realdata.getContent();
}
}

package com.example.design.future;

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;
}
}

package com.example.design.future;

//Main綾葷殑浠g爜

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");
  }
}

package com.example.design.future;

//Host 類的程式碼
public class Host {
public Data 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() {                             
            RealData realdata = new RealData(count, c);
            future.setRealData(realdata);
        }                                               
    }.start();                                          

    System.out.println("    request(" + count + ", " + c + ") END");

    // (3)取回FutureData例項,作為返回值
    return future;
}
}




相關文章