import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class CustomerQueue {
private static final int SIZE = 5000;
private LinkedList<String> queue = new LinkedList<String>();
private Lock lock = new ReentrantLock();
private Condition full = lock.newCondition();
private Condition empty = lock.newCondition();
private static CustomerQueue manager = new CustomerQueue();
private CustomerQueue(){
}
public static CustomerQueue getQueue(){
return manager;
}
public void put(String phone){
lock.lock();
try {
while (queue.size() == SIZE) {
full.await();
}
queue.addFirst(phone);
empty.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally{
lock.unlock();
}
}
public LinkedList<String> takeAll(){
LinkedList<String> retVal = new LinkedList<String>();
lock.lock();
try {
while (queue.size() == 0) {
empty.await();
}
retVal.addAll(queue);
queue.clear();
full.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally{
lock.unlock();
}
return retVal;
}
}
java 线程安全的队列模拟
最新推荐文章于 2024-04-15 08:30:00 发布