首页 > 其他 > 详细

用显式条件队列 写了一个简易队列 用于存取元素;

时间:2020-06-08 01:15:46      阅读:40      评论:0      收藏:0      [点我收藏+]

用显式条件队列  写了一个简易队列 用于存取元素;

实现条件;

取操作:当容器元素没多余时,读取操作挂起,释放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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!