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 線程安全的隊列模擬
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.