用显式条件队列 写了一个简易队列 用于存取元素;
实现条件;
取操作:当容器元素没多余时,读取操作挂起,释放CPU资源;阻塞
存操作:当容器内的容量达到上限后,存操作挂起,释放CPU资源,阻塞
import net.jcip.annotations.GuardedBy; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.AbstractQueuedSynchronizer.ConditionObject; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class ConditionDemo<T> { Lock lock = new ReentrantLock(); //条件谓词 count<array.length private Condition notFull = lock.newCondition(); //条件谓词 count>0 private Condition notEmpty = lock.newCondition(); private T[] items = (T[]) new Object[3]; @GuardedBy("lock") private int tails, head, count; public void put(T x) { lock.lock(); try { while (count == items.length) { System.out.println("当前容器已满,没有足够空间存放更多元素,请先释放..."); notFull.await(); } items[tails] = x; if (++tails == items.length) { tails = 0; } count++; notEmpty.signal(); } catch (InterruptedException e) { System.out.println(e.getMessage()); } finally { lock.unlock(); } } public T take() { lock.lock(); try { while (count == 0) { System.out.println("当期容器没有任何元素可供读取,请先存放元素到容器中..."); notEmpty.await(); } T x = items[head]; items[head] = null; if (++head == items.length) { head = 0; } --count; notFull.signal(); System.out.println("取出元素:" + x); return x; } catch (InterruptedException e) { System.out.println(e.getMessage()); } finally { lock.unlock(); } return null; } public static void main(String[] args) { ConditionDemo<String> conditionDemo = new ConditionDemo<>(); new Thread(() -> { conditionDemo.take(); }).start(); new Thread(() -> { conditionDemo.put("hello"); }).start(); } }
原文:https://www.cnblogs.com/zhangfengshi/p/13062710.html