1.創建Queue.java
public class Queue { private LinkedList<Object> list = new LinkedList<Object>() ; private final int minSize = 0 ; ; private final int maxSize ; private AtomicInteger count = new AtomicInteger(0) ; public Queue(int size){ this.maxSize = size ; } private final Object lock = new Object() ; public void put(Object o){ synchronized(lock){ while(size() == this.maxSize){ try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } list.add(o) ; //計數器增加 count.incrementAndGet() ; //通知喚醒 lock.notify(); } } private int size(){ return count.get() ; } public Object take(){ Object res = null ; synchronized(lock){ while(size() == this.minSize){ try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } res = list.removeFirst(); //計數器減1 count.decrementAndGet() ; lock.notify(); } return res ; } public static void main(String[] args) { final Queue mq = new Queue(3) ; mq.put("a"); mq.put("b"); mq.put("c"); new Thread(new Runnable() { @Override public void run() { mq.put("g"); System.out.println("put1 secceseful"); mq.put("f"); System.out.println("put2 secceseful"); } }).start(); new Thread(new Runnable() { @Override public void run() { System.out.println("take value = "+mq.take() ); } }).start(); } }
運行結果如下:
take value = a put1 secceseful
執行第一個put的時候由於隊列容量已經滿了,所以線程阻塞。另一個線程take之后,阻塞的線程繼續執行put成功。