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();
}
}
【代码积累】semaphore
最新推荐文章于 2022-04-06 12:40:01 发布