熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java進階:一個簡單Thread緩沖池的實現[2]

2022-06-13   來源: Java核心技術 

  把上面的內容結合起來就是一個SyncQueue的類

  public class SyncQueue {

  public SyncQueue(int size) {

  _array = new Object[size];

  _size = size;

  _oldest = ;

  _next = ;

  }

  public synchronized void put(Object o) {

  while (full()) {

  try {

  wait();

  } catch (InterruptedException ex) {

  throw new ExceptionAdapter(ex);

  }

  }

  _array[_next] = o;

  _next = (_next + ) % _size;

  notify();

  }

  public synchronized Object get() {

  while (empty()) {

  try {

  wait();

  } catch (InterruptedException ex) {

  throw new ExceptionAdapter(ex);

  }

  }

  Object ret = _array[_oldest];

  _oldest = (_oldest + ) % _size;

  notify();

  return ret;

  }

  protected boolean empty() {

  return _next == _oldest;

  }

  protected boolean full() {

  return (_next + ) % _size == _oldest;

  }

  protected Object [] _array;

  protected int _next;

  protected int _oldest;

  protected int _size;

  }

  可以注意一下get和put方法中while的使用如果換成if是會有問題的這是個很容易犯的錯誤;)

[]  []  []  


From:http://tw.wingwit.com/Article/program/Java/hx/201311/27222.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.