package com.study.thread; import java.util.LinkedList; import java.util.concurrent.atomic.AtomicInteger; public class MyQueueTest { private final static LinkedList<Object> list = new LinkedList<Object>(); private final AtomicInteger count = new AtomicInteger(); private int minSize = 0; private int maxSize; private Object lock = new Object(); public MyQueueTest(int maxSize){ this.maxSize = maxSize; } public void put(Object object){ synchronized (lock){ while (count.get()==this.maxSize){ try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } list.add(object); count.incrementAndGet(); lock.notify(); } } public Object take(){ Object object = null; synchronized (lock){ while (count.get()==this.minSize){ try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } object = list.removeFirst(); count.decrementAndGet(); lock.notify(); } return object; } public static void main(String[] args) { MyQueueTest myQueueTest = new MyQueueTest(4); myQueueTest.put("a"); myQueueTest.put("b"); myQueueTest.put("c"); myQueueTest.put("d"); System.out.println(myQueueTest.count); new Thread(new Runnable() { @Override public void run() { myQueueTest.put("e"); System.out.println("---------ok------------"); } }).start(); new Thread(new Runnable() { @Override public void run() { System.out.println(myQueueTest.take().toString()); } }).start(); } }
java发编程【一个demo 学习--queue(七)】
最新推荐文章于 2022-08-19 10:10:03 发布