【发布时间】:2015-01-23 04:42:18
【问题描述】:
我的代码 sn-p:
public class ProducerConsumerTest {
public static void main(String[] args)
{
ArrayBlockingQueue<String> sharedQueue = new ArrayBlockingQueue<String>(20, true);
ExecutorService consumerService = Executors.newFixedThreadPool(5);
ExecutorService producerService = Executors.newSingleThreadExecutor();
Future future=producerService.submit(new Producer(sharedQueue));
consumerService.execute(new Consumer(sharedQueue));
consumerService.execute(new Consumer(sharedQueue));
consumerService.execute(new Consumer(sharedQueue));
consumerService.execute(new Consumer(sharedQueue));
consumerService.execute(new Consumer(sharedQueue));
}
}
如何让主线程等待其他线程?
我面临的问题是我不知道ExecutorService 创建的线程的名称,这就是我不能使用join() 的原因。例如:t1.join() in main()。
【问题讨论】:
-
您期望从生产者服务中获得一些东西,但没有消费它?那么future.get()呢?还想知道为什么要等待主线程共存?如果您保存生产者/消费者的引用而不是在执行调用中释放它们,则可以拥有线程的引用。
-
你在 Web 应用程序中创建这个吗?
-
@OO7 不,这是一个普通的独立应用程序。
-
你的问题定义到底是什么?你会用它更新你的问题吗?以便更清楚地回答。
-
如果主线程有任务要执行,该任务会影响是否以及如何等待。但如果主线程无事可做,就让它结束吧。阻止相关资源没有任何好处。
标签: java multithreading threadpool executorservice