当前位置:首页 > 开发 > 编程语言 > 编程 > 正文

Condition的阻塞队列

发表于: 2014-07-07   作者:a67474506   来源:转载   浏览:
摘要: package cn.zto.condition; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; //阻塞队列 public class ConditionTe
package cn.zto.condition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//阻塞队列
public class ConditionTest {
	Lock lock = new ReentrantLock();
	
	Condition notFull = lock.newCondition();
	Condition notEmpty = lock.newCondition();
	
	Object [] items = new Object[100] ;
	
	int putptr , takeptr , count;
	
	public void put (Object x) throws InterruptedException {
		lock.lock();
		try {
			while(count == items.length)
				notFull.await();
			items[putptr] = x ;
			if (++putptr == items.length) putptr = 0;
			count++;
			notEmpty.signal();
		} finally {
			lock.unlock();
		}
	}
	
	public Object take() throws InterruptedException {
		lock.lock();
		try {
			while(count == 0)
				notEmpty.await();
			Object x = items[takeptr];
			if (++takeptr == items.length) takeptr = 0;
			count--;
			notFull.signal();
			return x;
		} finally {
			lock.unlock();
		}
	}
}

 

 

Condition的阻塞队列

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号