此框架提高了请求的并发效率。服务端维护了一个队列(池),处理请求。 package test; public class Test { /** * 分离服务的请求和服务的执行,使得可以对服务请求排队。提高请求并发效率。 * * @param args */ public static void main(String[] args) { Service s = new ServiceProxy(); Client c = new Client(s); c.requestService(); } } package test; interface Service { public void sayHello(); } package test; class ServiceImp implements Service { public void sayHello() { System.out.println("Hello World!"); } } package test; /** * 服务接收请求,并在队列(池)中维护请求。 * * @author david * */ class ServiceProxy implements Service { public ServiceProxy() { service = new ServiceImp(); activeObject = new ActiveObject(); } public void sayHello() { MethodRequest mr = new SayHello(service); activeObject.enqueue(mr); } private Service service; private ActiveObject activeObject;// 维护一个请求服务队列(池) } package test; class SayHello implements MethodRequest { public SayHello(Service s) { service = s; } public void call() { service.sayHello(); } private Service service; } package test; interface MethodRequest { public void call(); } package test; /** * 活动对象。相当于一个处理队列(池)的线程。 * * @author david * */ class ActiveObject extends Thread { public ActiveObject() { queue = new ActiveQueue(); start(); } public void enqueue(MethodRequest mr) { queue.enqueue(mr); } public void run() { while (true) {// 监控队列 MethodRequest mr = queue.dequeue(); mr.call(); } } private ActiveQueue queue; } package test; import java.util.Stack; /** * 活动队列(池) * * @author david * */ class ActiveQueue { public ActiveQueue() { queue = new Stack<MethodRequest>(); } /** * 入池 * * @param mr */ public synchronized void enqueue(MethodRequest mr) { while (queue.size() > QUEUE_SIZE) {// 池满,等待 try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } queue.push(mr); notifyAll();// * System.out.println("Leave Queue"); } /** * 出池 * * @return */ public synchronized MethodRequest dequeue() { MethodRequest mr; while (queue.empty()) {// 池空,等待 try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } mr = (MethodRequest) queue.pop(); notifyAll();// * return mr; } private Stack<MethodRequest> queue; private final static int QUEUE_SIZE = 20;// 池大小 } 参考:http://www.ibm.com/developerworks/cn/java/l-multithreading/