`

java 线程

阅读更多
http://zhidao.baidu.com/question/173605083.html


编一个小程序:
用ArrayList作为缓存容器(非线程安全的),用java读写锁的形式实现对该容器的读、写操作
快的话追加:)我来帮他解答 输入内容已经达到长度限制还能输入 9999 字插入图片删除图片插入地图删除地图插入视频视频地图回答即可得2分经验值,回答被选为满意回答可同步增加经验值和财富值
参考资料:匿名回答提交回答取消
       2010-8-10 11:06 满意回答 /**
* <p>Title: 先进先出队列</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2009</p>
* <p>Company: </p>
* @author wangyou
* @version 2.0
*/
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class FIFOMsgQueue<T> {
private final int DEFAULT_CAPABILITY = 10000;
private int capability;
private LinkedList<T> msgQueue = new LinkedList<T>();
private Object lock = new Object();

/**
  * 默认的构造方法,其生成的队列的容量大小为默认的10000
  */
public FIFOMsgQueue() {
  this.capability = DEFAULT_CAPABILITY;
}

/**
  * 生成指定容量大小的队列
  *
  * @param capability
  *            队列容量大小
  */
public FIFOMsgQueue(int capability) {
  this.capability = capability;
}

/**
  * 判断队列是否已满
  *
  * @return
  */
public boolean isFull() {
  return (msgQueue.size() == capability ? true : false);
}

/**
  * 返回队列的容量大小
  *
  * @return
  */
public int capability() {
  return capability;
}

/**
  * 返回当前队列大小
  *
  * @return
  */
public int size() {
  return msgQueue.size();
}

/**
  * 返回当前队列是否为空
  *
  * @return
  */
public boolean isEmpty() {
  return (msgQueue.size() <= 0 ? true : false);
}

/**
  * 将指定内容元素message放入队列中
  *
  * @param message
  *            指定放入队列中的内容元素
  */
public void push(T message) {
  synchronized (lock) {
   if (isFull()) {
    try {
     lock.wait();
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
   msgQueue.addLast(message);
  }
}

/**
  * 取出队列中第一个内容元素
  *
  * @return 队列中第一个内容元素
  */
public T pop() {
  synchronized (lock) {
   T message = null;
   if (!isEmpty()) {
    message = (T) msgQueue.removeFirst();
    lock.notifyAll();
   }
   return message;
  }
}

/**
  * 取出队列中指定个数的内容元素
  *
  * @param num
  *            取出队列中的内容元素个数
  * @return
  */
public List<T> pop(int num) {
  synchronized (lock) {
   LinkedList<T> messages = new LinkedList<T>();
   for (int i = 0; i < num; i++) {
    if (!isEmpty()) {
     messages.addLast(this.pop());
    } else {
     break;
    }
   }
   lock.notifyAll();
   return messages;
  }
}

/**
  * 返回指定队列索引处的内容元素
  *
  * @param index
  *            队列内容元素索引
  * @return 指定索引处的内容元素
  */
public T get(int index) {
  T message = null;
  if (isEmpty()) {
   message = (T) msgQueue.get(index);
  }
  return message;
}

/**
  * 移除队列指定索引处的内容元素
  *
  * @param index
  *            队列内容元素索引
  * @return 移除的内容元素
  */
public T remove(int index) {
  synchronized (lock) {
   T message = null;
   if (!isEmpty()) {
    message = (T) msgQueue.remove(index);
    lock.notifyAll();
   }
   return message;
  }
}

/**
  * 获取队列迭代器
  *
  * @return 队列迭代器
  */
public Iterator<T> iterator() {
  return msgQueue.iterator();
}

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics