【代码积累】semaphore

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;


public class OperationQueue<T> {
	private LinkedBlockingQueue<T> queue = null;
	private Semaphore semaphore = new Semaphore(1);
	
	public OperationQueue(int capacity) {
		queue = new LinkedBlockingQueue<T>(capacity);
	}
	
	public void addElement(T element) {
		try {
			queue.put(element);  /*如果要使用LBQ的阻塞特性,一定要使用put/take方法*/
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public T getElement() {
		T t = null;
		
		try {
			/*对于一个线程,并没有持有信号量一说,对信号量的操作只是改变信号量的permits的数值,当permits为0时,试图acquire信号量的线程被挂起,直到permits非0*/
			semaphore.acquire();  /*默认支持中断,抛异常。线程被挂起期间,可被中断,响应中断后标志位清除。*/
			System.out.println("EventConsumer gets SEMAPHORE.");
			t = get();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			semaphore.release(); /*increase permits by one,or increase by a given amount*/
		}
		/*无异常,则不释放信号量,由handler来释放信号量*/
		return t;
	}
	
	public void releaseSemaphore() {
		semaphore.release();
	}
	
	public T get() {
		T t = null;
		
		try {
			t = queue.take(); /*注意LBQ的poll方法在队列为空时不会阻塞,直接返回null,而take方法会阻塞*/
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return t;
	}
	
	public boolean isEmpty() {
		return queue.isEmpty();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值