4. SingleThreadedExecution public class Gate { private String people= "Nobody"; private String address = "Nowhere"; public synchronized void pass(String people) { //只有一个人通过这扇门 } public String getGateName() { // } }
5. Immutable 典型代表:String类 例子: public final class Person { privatefinal String name; //no setter public Person(String name) { this.name = name; } public String getName() { return name; } }
18. Thread-Per-Message private final Helper helper = new Helper(); public void request(final int p1, final char p2) { new Thread() { public void run() { helper.handle(p1, p2); } }.start(); }
22. Future public Data create(final int param1, final char param1) { // (1) 建立FutureData的实体 final FutureData future = new FutureData(); // (2) 为了建立RealData的实体,启动新的线程 new Thread() { public void run() { RealDatarealdata = new RealData(param1, param2); future.setRealData(realdata); } }.start(); // (3)返回FutureData实体 return future; }
23. Future public class RealData implements Data { private final String content; public RealData(int param1, char param2) { //do something, burn time this.content = new String(buffer); } public String getContent() { return content; } }
24. Future public class FutureData implements Data { private RealDatarealdata = null; private booleanready = false; public synchronized void setRealData(RealDatarealdata) { if (ready) return; // balking this.realdata = realdata; this.ready= true; notifyAll(); } public synchronized String getContent() { while (!ready) { //garded try { wait(); } catch (InterruptedException e) { } } return realdata.getContent(); } }