我有几个使用ArrayBlockingQueue的工作者。
每个工作者从队列中取出一个对象进行处理,可能会得到多个对象作为结果,这些对象将被放入队列以供进一步处理。因此,工作者=生产者+消费者。
工作者:
public class Worker implements Runnable
{
private BlockingQueue<String> processQueue = null;
public Worker(BlockingQueue<String> processQueue)
{
this.processQueue = processQueue;
}
public void run()
{
try
{
do
{
String item = this.processQueue.take();
ArrayList<String> resultItems = this.processItem(item);
for(String resultItem : resultItems)
{
this.processQueue.put(resultItem);
}
}
while(true);
}
catch(Exception)
{
...
}
}
private ArrayList<String> processItem(String item) throws Exception
{
...
}
}
主要内容:
public class Test
{
public static void main(String[] args) throws Exception
{
new Test().run();
}
private void run() throws Exception
{
BlockingQueue<String> processQueue = new ArrayBlockingQueue<>(10000);
processQueue.put("lalala");
Executor service = Executors.newFixedThreadPool(100);
for(int i=0; i<100; ++i)
{
service.execute(new Worker(processQueue));
}
}
}
没有更多的工作时,最好的停止工作方式是什么?
首先,我的想法是定期检查队列中有多少项和当前处理的项。如果两者均为零,则在ExecutorService上执行类似于“shutdownNow()”的操作。但我不确定这是否是最佳方法。