package cn.com.qmth.examcloud.core.questions.base.multithread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class Consumer<T> extends Thread {

    private static final Logger LOG = LoggerFactory.getLogger(Consumer.class);

    private Basket basket;
    
    private Consumer<T> consumer;

    public Consumer() {
    }
    
    
    public Consumer<T> getConsumer() {
        return consumer;
    }

    
    public void setConsumer(Consumer<T> consumer) {
        this.consumer = consumer;
    }



    @Override
    public void run() {
        try {
            while (true) {
                // 先判断是否有异常结束
                if (basket.isExcuteError()) {
                    break;
                }
                // 取消费数据
                Object o = basket.consume();
                // 判断消费数据是否是结束
                if (o instanceof EndObject) {
                    break;
                }
                @SuppressWarnings("unchecked")
                T t = (T) o;
                // 消费数据实现
                int disposeCount = consumer.consume(t);
                if (basket.getTotal() > 0) {
                    basket.updateProcess(disposeCount);
                    processInfo();
                }
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            basket.setExcuteError(true);
        } finally {
            basket.countDown();
        }
    }

    protected abstract int consume(T t);

    protected void setBasket(Basket basket) {
        this.basket = basket;
    }
    protected Basket getBasket() {
        return this.basket;
    }
    protected void processInfo() {
        LOG.warn(basket.getTaskName()+" 处理进度" + basket.getProgress());
    }
}
