【线程数据队列操作】


import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;


public abstract class WorkerThread
		extends Thread {

	protected static final Logger log = Logger.getLogger(WorkerThread.class.getName());

	private long averageProcessingTime = 0;

	//private PriorityQueueAbstract<QueueItem> queue = null;
	private LinkedBlockingQueue<QueueItem> queue = null;
	private long runsCnt = 0;
	private boolean stopped = false;

	public abstract WorkerThread getNewInstance();

	public abstract void process(QueueItem item);

	public long getAverageProcessingTime() {
		return averageProcessingTime;
	}

	public long getRunsCounter() {
		return runsCnt;
	}

	public boolean offer(QueueItem item) {
		return queue.offer(item);
	}

	@Override
	public void run() {
		QueueItem item = null;

		while (!stopped) {
			try {
				item = queue.take();

				long start = System.currentTimeMillis();

				process(item);

				long end = System.currentTimeMillis() - start;

				if (end > 0) {
					averageProcessingTime = (averageProcessingTime + end) / 2;
				}
			} catch (Exception e) {
				if (!stopped) {
					log.log(Level.SEVERE,
							this.getClass().getName() + ",(" + getName() + ") Exception during packet processing: " +
									item.getPacket(), e);
				}
			}

			++runsCnt;
		}
	}

	public void setQueueMaxSize(int maxSize) {
		LinkedBlockingQueue<QueueItem> oldQueue = queue;

		queue = new LinkedBlockingQueue<QueueItem>(maxSize);

		if (oldQueue != null) {
			queue.addAll(oldQueue);
		}
	}

	public int size() {
		return queue.size();
	}

	public void shutdown() {
		stopped = true;
		try {
			this.interrupt();
		} catch (Exception ex) {
		}
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值