這裏定義了一個有界隊列 ,保證先進先出,在隊列達到上限時應該阻塞,直到隊列有元素被取出才能繼續往裏繼續添加java
完整代碼:ide
package com.comic.queue; import java.util.LinkedList; import java.util.concurrent.atomic.AtomicInteger; public class BoundedQueue { // 隊列的最大值 private int maxSize; // 計數器 private AtomicInteger counter = new AtomicInteger(0); // 數據容器 private LinkedList<Object> content = new LinkedList<Object>(); // 瑣 private Object lock = new Object(); public BoundedQueue(int maxSize) { this.maxSize = maxSize; } /** * 入隊列 * * @param obj * @throws InterruptedException */ public void put(Object obj) throws InterruptedException { synchronized (lock) { while (maxSize == counter.get()) { System.out.println("隊列已滿,請等待...."); lock.wait(); } // 添加元素,計數,喚醒線程 content.add(obj); counter.getAndIncrement(); lock.notify(); System.out.println(obj + "入列"); } } /** * 取 * * @return * @throws InterruptedException */ public Object take() throws InterruptedException { Object obj = null; synchronized (lock) { while (0 == counter.get()) { System.out.println("隊列已空,請等待...."); lock.wait(); } // 獲取第一個元素,計數,喚醒線程 obj = content.get(0); content.remove(0); counter.decrementAndGet(); lock.notify(); } return obj; } public static void main(String[] args) throws InterruptedException { final BoundedQueue queue = new BoundedQueue(5); queue.put("aa"); queue.put("bb"); queue.put("cc"); queue.put("dd"); queue.put("ff"); Thread t = new Thread(new Runnable() { @Override public void run() { try { queue.put("gg"); queue.put("hh"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }, "t1"); t.start(); Thread.sleep(500); System.out.println("**********************************"); Thread t2 = new Thread(new Runnable() { @Override public void run() { try { System.out.println("take:" + queue.take()); System.out.println("take:" + queue.take()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }, "t2"); t2.start(); } }
控制檯部分:this
aa入列 bb入列 cc入列 dd入列 ff入列 隊列已滿,請等待.... ********************************** take:aa gg入列 隊列已滿,請等待.... take:bb hh入列