Difference between Executors.newFixedThreadPool(1) and Executors.newSingleThreadExecutor()
我的问题是:使用
PS:主线程和oneAnotherThread不访问任何公共资源。
我经历了:使用ExecutorService有什么优势? 一次只能有一个线程!
does it make sense to use
Executors.newFixedThreadPool(1) ?
它与
In two threads (main + oneAnotherThread) scenarios is it efficient to use executor service?
执行程序服务是围绕线程的非常薄的包装器,可显着促进线程生命周期管理。如果您唯一需要的是
在任何现实生活中,都有可能监视任务的生命周期(通过返回的
底线:我看不到使用执行程序服务和线程的任何缺点。
Executors.newSingleThreadExecutor()。execute(command)和new Thread(command).start();之间的区别经历了两个选项之间行为上的细微差异。
does it make sense to use Executors.newFixedThreadPool(1)??
是。如果您要按到达顺序处理所有已提交的任务,这很有意义
In two threads (main + oneAnotherThread) scenarios is it efficient to use executor service? Is creating a new thread directly by calling new Runnable(){ } better than using ExecutorService?.
我更喜欢
请参阅以下SE问题以获取
ExecutorService与Casual Thread Spanner
What are the upsides and downsides of using ExecutorService for such scenarios?
看看与ExexutorService用例有关的SE问题:
Javas Fork / Join与ExecutorService-什么时候使用?
关于主题行中的查询(来自grepcode),两者相同:
1 2 3 4 | public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); |
和
1 2 3 4 5 | public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); |
我同意@assylias关于相似性/差异性的答案。
有时需要使用
1 2 3 4 5 6 | private final ExecutorService executor = Executors.newFixedThreadPool(1); public int getTaskInQueueCount() { ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor; return threadPoolExecutor.getQueue().size(); } |
通过调用new Runnable(){}直接创建新线程是否比使用ExecutorService更好?
如果要在线程编译后对返回的结果进行计算,则可以使用Callable接口,该接口只能与ExecutorService一起使用,而不能与new Runnable(){}一起使用。 ExecutorService的Submit()方法以Callable对象为依据,它返回Future对象。在此Future对象上,如果不使用isDone()方法,则检查任务是否已完成。您也可以使用get()方法获得结果。
在这种情况下,ExecutorService优于新的Runnable(){}。