import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicInteger;
import com.sun.org.apache.xerces.internal.parsers.CachingParserPool.SynchronizedGrammarPool;
public class MyQueue {
private LinkedList<Object> list = new LinkedList<Object>();
private AtomicInteger count = new AtomicInteger(0);
private int minSize = 0;
private int maxSize;
public MyQueue(int size){
this.maxSize = size;
}
private final Object lock = new Object();
public void put(Object obj){
System.out.println("Put .... before lock");;
synchronized(lock){
while(count.get() == this.maxSize){
try {
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Put .... after lock");;
list.add(obj);
System.out.println("新加入的元素 :"+obj);
count.incrementAndGet();
lock.notify();
}
}
public Object take(){
Object reuslt = null;
System.out.println("Take .... before lock");;
synchronized(lock){
while(count.get() == this.minSize){
try {
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Take .... after lock");;
reuslt = list.removeFirst();
System.out.println("移除的元素:"+reuslt);
count.decrementAndGet();
lock.notify();
}
return reuslt;
}
public int getSize(){
return this.count.get();
}
public static void main(String[] args){
MyQueue myQueue = new MyQueue(5);
myQueue.put("1");
myQueue.put("2");
myQueue.put("3");
myQueue.put("4");
myQueue.put("5");
System.out.println("容器长度: "+myQueue.getSize());
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
myQueue.put("6");
myQueue.put("7");
// TODO Auto-generated method stub
}
},"t1" );
t1.start();
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stubQ
Object o = myQueue.take();
Object o1 = myQueue.take();
}
},"t2");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t2.start();
}
}
以下代码模拟了阻塞的队列过程