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) {
}
}
}
【线程数据队列操作】
于 2022-04-08 10:34:30 首次发布