package threadtest; import java.util.LinkedList; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public class QueueTest01 { private LinkedList<Object> list = new LinkedList<Object>(); private AtomicInteger count = new AtomicInteger(0); private final int minSize = 0; private final int maxSize; public QueueTest01(int maxsize) { this.maxSize = maxsize; } private final Object lock = new Object(); public void put(Object obj) { synchronized (lock) { while (this.maxSize == count.get()) { try { lock.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } list.add(obj); count.incrementAndGet(); System.out.println("新加入的元素是:" + obj); lock.notify(); } } public Object take() { Object obj = null; synchronized (lock) { while (this.minSize == count.get()) { try { lock.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } obj = list.removeFirst(); count.decrementAndGet(); lock.notify(); } return obj; } public static void main(String[] args) { final QueueTest01 myQueue = new QueueTest01(5); myQueue.put("a"); myQueue.put("b"); myQueue.put("c"); myQueue.put("d"); myQueue.put("e"); System.out.println("当前对列的长度:" + myQueue.list.size()); Thread t1 = new Thread(new Runnable() { @Override public void run() { myQueue.put("f"); myQueue.put("g"); } }, "t1"); t1.start(); Thread t2 = new Thread(new Runnable() { @Override public void run() { Object o1 = myQueue.take(); System.out.println("移除的元素为:" + o1); Object o2 = myQueue.take(); System.out.println("移除的元素为:" + o2); } }, "t2"); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } t2.start(); } }
时间: 2024-12-14 17:23:04