Java 使用 Executors.newSingleThreadExecutor() 的优势
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19000324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Advantage of using Executors.newSingleThreadExecutor()
提问by Abichellam
What is the advantageof using
使用的好处是什么
Executors.newSingleThreadExecutor().submit(job);
than
比
job.run();
where job
is an instance of Runnable
class.
哪里job
是Runnable
类的实例。
回答by Drona
The difference is same as in new Thread(job).start()
and job.run()
. When you submit the job for execution, the job runs in one of the available thread of the executor. Calling job.run()
is simply like any other method call which does not run in a separate thread but rather on the calling thread.
区别与new Thread(job).start()
和相同job.run()
。当您提交作业以供执行时,该作业将在执行程序的可用线程之一中运行。调用job.run()
就像任何其他方法调用一样,它不在单独的线程中运行,而是在调用线程上运行。
回答by Luca Mastrostefano
One of the advantage is that Executors.newSingleThreadExecutor reuse the Thread instance to speed up the starting of the other jobs.
好处之一是 Executors.newSingleThreadExecutor 重用了 Thread 实例来加速其他作业的启动。
回答by Marko Topolnik
Writing literally
字面书写
Executors.newSingleThreadExecutor().submit(job);
is pointless: it's just the wrong way to do
毫无意义:这只是错误的做法
new Thread(job).start();
As opposed to the latter, the former will leave the thread hanging on until the Executor Service is finalized.
与后者相反,前者将保持线程挂起,直到 Executor Service 完成。
The advantageof using an Executor Service comes about when you keep it around as an instance/class variable and reuse it for many submitted tasks. The Executor Service must be properly shutdown
when you are done with it.
当您将 Executor Service 作为实例/类变量保留并在许多提交的任务中重用它时,就会产生使用 Executor Service的优势。Executor Service 必须shutdown
在您完成后正确运行。
More generally, the difference between submitting tasks to an executor service and just running the tasks is in the achieved concurrency. Whether that results in any advantage is highly specific to the job being submitted: it may also be useless or even broken (causing data races, deadlocks, etc.).
更一般地说,将任务提交给执行程序服务与仅运行任务之间的区别在于实现的并发性。这是否会带来任何优势取决于提交的作业:它也可能无用甚至损坏(导致数据竞争、死锁等)。