多线程设计模式 -- suspension
2009-09-17 00:00:00 来源:WEB开发网工作缓存器jdk1.5新特性实现
Java代码
public class RequestQueue {
private final LinkedList queue = new LinkedList();
private Lock lock = new ReentrantLock();
private Condition serverCondition = lock.newCondition();
private Condition clientCondition = lock.newCondition();
public Request getRequest() {
lock.lock();
try {
while (queue.size() <= 0) {
//类似wait();
serverCondition.await();
}
} catch (InterruptedException e) {
} finally {
lock.unlock();
}
return (Request) queue.removeFirst();
}
public void putRequest(Request request) {
lock.lock();
try {
queue.addLast(request);
//类似notifyAll();
clientCondition .signalAll();
} finally {
lock.unlock();
}
}
}
工作缓存器jdk1.5新特性实现
Java代码
public class NewRequestQueue {
//一个特殊的Queue下面有详细的说明
private final static BlockingQueue<Request> basket = new ArrayBlockingQueue<Request>(
10);;
public Request getRequest() {
try {
return basket.take();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void putRequest(Request request) {
try {
basket.put(request);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Tags:线程 设计模式 suspension
编辑录入:爽爽 [复制链接] [打 印]更多精彩
赞助商链接