多线程的PipeLine实现实例

本文介绍了如何使用多生产者多消费者的Blocking Queue实现PipeLine调度框架,详细阐述了Worker类在框架中的作用。

多生产者多消费者的Blocking Queue

/**
 * A blocking queue which wraps {@code ArrayBlockingQueue}, and with the
 * following features. 
 * <li>Use null object as end of queue.
 * <li>Supports muti-producers for the queue. Only if all the producers put a position-pill to
 * the queue, the queue will reach end of life.
 * 
 * @param <T>
 *            element type
 */
public class Queue<T> {
    
    private ArrayBlockingQueue<Element<T>> queue = null;
    
    private AtomicInteger lifeValue ;   
    
    private static int DEFAULT_LIFE_VALUE = 1;
    
    /**
     * 
     * @param capacity The queue size
     * @param lifeValue It is set as the number of producer of the queue as a rule
     */
    public Queue(int capacity, int lifeValue) {
        this.queue = new ArrayBlockingQueue<Element<T>>(capacity);
        this.lifeValue = new AtomicInteger(lifeValue);
    }
       
    public Queue(int capacity) {
        this( capacity, DEFAULT_LIFE_VALUE );
    }
    
    /**
     * Put an position-pill to the queue.  
     * @throws InterruptedException
     */
    @SuppressWarnings("unchecked")
    public void putEnd() throws InterruptedException{
        int life = this.lifeValue.decrementAndGet();
        if(life <= 0 ){
            this.queue.put(Element.NULL);
        }
    }
    
    /**   
     * Put an element to the queue
     * @param element
     * @throws InterruptedException
     */
    public void put(T element ) throws InterruptedException{
        try {
            queue.put(new Element<T>(element));
        } catch (InterruptedException e) {
            this.queue.clear();
            throw e;
        }
    }
    
    /**
     * Take an element from the head of queue. 
     * If queue is empty, the operation will be blocked.
     * 
     * @return a non-nullable object if queue if not empty, or null if the queue is ended
     * @throws InterruptedException 
     */
    public T take() throws InterruptedException{
        Element<T> element = this.queue.take();
        if( Element.NULL == element){
            this.queue.put(Element.NULL);
        }
        return element.getObject();        
    } 
    
    /**
     * Take elements in batch from the queue. The operation will be blocked for a non-ended queue.
     * The fetched list size should be equal to count unless the queue is ended
     * @param count the desired element size to fetch
     * @return a List which contains the batch fetched element, or null if the queue is ended and empty
     * @throws InterruptedException
     */
    public List<T> batchTake(int count) throws InterruptedExcept
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值