我想知道我对使用 ExecutorService 和 ArrayBlockingQueue 的生产者消费者设计的理解是否正确。我知道有不同的方法来实现这个设计,但我想,最终,这取决于问题本身。
我必须面对的问题是:我有一个制作人,他从一个大文件(6GB)中读取;它逐行读取并将每一行转换为一个对象。它将对象放入 ArrayBlockingQueue 中。
消费者(少数)从 ArrayBlockingQueue 中获取对象并将其保存到数据库中。
现在,显然生产者比消费者快得多;将每一行转换为对象需要几分之一秒的时间,但对于消费者来说需要更长的时间。
所以...如果我希望通过这样做来加速这个过程:我创建了 2 个类“ProducerThread”和“ConsumerThread”,它们共享 ArrayBlockingQueue。两者之间协调的线程如下所示:
@Override
public void run()
{
try{
ArrayBlockingQueue<Ticket> queue = new ArrayBlockingQueue<Ticket>(40);
ExecutorService threadPool = Executors.newFixedThreadPool(8);
threadPool.execute(new SaleConsumerThread("NEW YORK", queue));
threadPool.execute(new SaleConsumerThread("PARIS", queue));
threadPool.execute(new SaleConsumerThread("TEL AVIV", queue));
threadPool.execute(new SaleConsumerThread("HONG KONG", queue));
threadPool.execute(new SaleConsumerThread("LONDON", queue));
threadPool.execute(new SaleConsumerThread("BERLIN", queue));
threadPool.execute(new SaleConsumerThread("AMSTERDAM", queue));
Future producerStatus = threadPool.submit(new SaleProducerThread(progressBar, file, queue));
producerStatus.get();
threadPool.shutdown();
}catch(Exception exp)
{
exp.printStackTrace();
}
}
我的问题是:
上面的设计实际上会使用每个线程吗同时?我的电脑是两个 2.4GHz 四核。
我不确定 Future 和 .get() 的用途是什么?
顺便说一句,结果很快(考虑到第一个版本是连续的,花了 3 小时),现在大约需要 40 分钟(但也许还有改进的空间)。
感谢您的任何指点