我的问题是:使用Executors.newFixedThreadPool(1)??是否有意义。在两个线程(main + oneAnotherThread)场景中,使用executor服务有效吗?通过调用new Runnable(){ }直接创建一个新线程比使用ExecutorService更好吗?在这种情况下使用ExecutorService有什么好处和缺点?
主线程和oneAnotherThread不访问任何公共资源。
发布于 2014-01-23 06:37:52
使用
Executors.newFixedThreadPool(1)有意义吗?
这与Executors.newSingleThreadExecutor()本质上是一样的,只是后者不是可重构的,正如javadoc中所指出的那样,而前者则是将其转换为ThreadPoolExecutor的话。
在两个线程(main + oneAnotherThread)场景中,使用executor服务有效吗?
executor服务是一个非常薄的线程包装器,它极大地便利了线程生命周期的管理。如果您唯一需要的是new Thread(runnable).start();并继续前进,那么就不需要真正的ExecutorService了。
在任何现实生活中,监视任务生命周期的可能性(通过返回的Future)、执行者将根据需要重新创建线程(在出现不明确的异常情况下)、回收线程与创建新线程的性能增益等等,使执行器服务成为一种更强大的解决方案,而不需要额外的成本。
底线:我不认为使用executor服务对线程有什么坏处。
Executors.newSingleThreadExecutor().execute(command)与新线程(命令).start()的区别;经历了这两种选择在行为上的细微差别。
发布于 2016-01-28 16:53:14
有时需要使用Executors.newFixedThreadPool(1)来确定队列中的任务数。
private final ExecutorService executor = Executors.newFixedThreadPool(1);
public int getTaskInQueueCount() {
ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor;
return threadPoolExecutor.getQueue().size();
}发布于 2016-01-28 19:00:45
使用Executors.newFixedThreadPool(1)有意义吗??
是。如果您想按照到达的顺序处理所有提交的任务,这是有意义的。
在两个线程(main + oneAnotherThread)场景中,使用executor服务有效吗?通过调用new (){}来直接创建一个新线程比使用ExecutorService更好吗?
我更喜欢ExecutorService或ThreadPoolExecutor,即使是一个线程。
有关ThreadPoolExecutor相对于新Runnable()的优势的解释,请参阅下面的SE问题:
在这种情况下使用ExecutorService有什么好处和缺点?
查看有关ExexutorService用例的相关SE问题:
Java/Join与ExecutorService -什么时候使用哪种?
对于主题行中的查询(来自grepcode),两者是相同的:
newFixedThreadPool API将以ExecutorService的形式返回ThreadPoolExecutor:
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());和
newSingleThreadExecutor()返回ThreadPoolExecutor作为ExecutorService:
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));我同意@assylias关于相似之处的回答。
https://stackoverflow.com/questions/21300924
复制相似问题