WEB开发网
开发学院软件开发Java 多线程设计模式 -- suspension 阅读

多线程设计模式 -- suspension

 2009-09-17 00:00:00 来源:WEB开发网   
核心提示: 工作缓存器jdk1.5新特性实现 Java代码publicclassRequestQueue{privatefinalLinkedListqueue=newLinkedList();privateLocklock=newReentrantLock();privateConditionserver

工作缓存器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); 
 } 
 } 
 
}

上一页  1 2 3 4  下一页

Tags:线程 设计模式 suspension

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接