我们什么时候应该使用 Java 的 Thread 而不是 Executor?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1094867/
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
When should we use Java's Thread over Executor?
提问by ripper234
Executor seems like a clean abstraction. When would you want to use Thread directly rather than rely on the more robust executor?
Executor 似乎是一个干净的抽象。你什么时候想直接使用 Thread 而不是依赖更健壮的执行器?
采纳答案by Pablojim
To give some history, Executors were only added as part of the java standard in Java 1.5. So in some ways Executors can be seen as a new better abstraction for dealing with Runnable tasks.
为了提供一些历史,Executors 只是作为 Java 1.5 中 Java 标准的一部分添加的。所以在某些方面 Executors 可以被看作是处理 Runnable 任务的新的更好的抽象。
A bit of an over-simplification coming... - Executors are threads done right so use them in preference.
有点过度简化了...... - 执行器是正确完成的线程,因此优先使用它们。
回答by skaffman
There is no advantage to using raw threads. You can always supply Executors with a Thread factory, so even the option of custom thread creation is covered.
使用原始线程没有任何优势。您始终可以为 Executors 提供一个线程工厂,因此甚至涵盖了自定义线程创建的选项。
回答by akarnokd
I use Thread when I need some pull based message processing. E.g. a Queue is take()-en in a loop in a separate thread. For example, you wrap a queue in an expensive context - lets say a JDBC connection, JMS connection, files to process from single disk, etc.
当我需要一些基于拉取的消息处理时,我使用 Thread。例如,队列在单独线程中的循环中是 take()-en。例如,您将队列包装在一个昂贵的上下文中 - 比如说 JDBC 连接、JMS 连接、要从单个磁盘处理的文件等。
Before I get cursed, do you have some scenario?
在我被诅咒之前,你有什么剧本吗?
Edit:
编辑:
As stated by others, the Executor
(ExecutorService
) interface has more potential, as you can use the Executors
to select a behavior: scheduled, prioritized, cached etc. in Java 5+ or a j.u.c backport for Java 1.4.
正如其他人所说,Executor
( ExecutorService
) 接口具有更大的潜力,因为您可以使用Executors
来选择行为:Java 5+ 中的调度、优先级、缓存等或 Java 1.4 的 juc 向后移植。
The executor framework has protection against crashed runnables and automatically re-create worker threads. One drawback in my opinion, that you have to explicitly shutdown()
and awaitTermination()
them before you exit your application - which is not so easy in GUI apps.
If you use bounded queues you need to specify a RejectedExecutionHandler
or the new runnables get thrown away.
执行器框架可以防止崩溃的可运行程序并自动重新创建工作线程。在我看来,一个缺点是您必须在退出应用程序之前明确地shutdown()
和awaitTermination()
它们 - 这在 GUI 应用程序中并不容易。如果您使用有界队列,则需要指定 aRejectedExecutionHandler
否则新的可运行对象将被丢弃。
You might have a look at Brian Goetz et al: Java Concurrency in Practice (2006)
回答by nojevive
You don't use Thread unless you need more specific behaviour that is not found in Thread itself. You then extend Thread and add your specifically wanted behaviour.
除非您需要在 Thread 本身中找不到的更具体的行为,否则不要使用 Thread。然后您扩展 Thread 并添加您特别想要的行为。
Else just use Runnable or Executor.
否则只需使用 Runnable 或 Executor。
回答by SoulWanderer
Well, I thought that a ThreadPoolExecutor provided better performance for it manages a pool of threads, minimizing the overhead of instantiating a new thread, allocating memory...
好吧,我认为 ThreadPoolExecutor 提供了更好的性能,因为它管理线程池,最小化实例化新线程的开销,分配内存......
And if you are going to launch thousands of threads, it gives you some queuing functionality you would have to program by yourself...
如果您要启动数千个线程,它会为您提供一些您必须自己编程的排队功能......
Threads & Executors are different tools, used on different scenarios... As I see it, is like asking why should I use ArrayList when I can use HashMap? They are different...
Threads & Executors 是不同的工具,用在不同的场景中......在我看来,就像在问为什么我可以使用 HashMap 时我应该使用 ArrayList?它们是不同的...
回答by Reachgoals
java.util.concurrent package provides executor interface and can be used to created thread.
java.util.concurrent 包提供了执行器接口,可用于创建线程。
The Executor interface provides a single method, execute, designed to be a drop-in replacement for a common thread-creation idiom. If r is a Runnable object, and e is an Executor object you can replace
Executor 接口提供了一个单一的方法,execute,旨在替代常见的线程创建习惯用法。如果 r 是一个 Runnable 对象,而 e 是一个 Executor 对象,你可以替换
(new Thread(r)).start();
(新线程(r)).start();
with
和
e.execute(r);
e.执行(r);
Refer here
参考这里
回答by Ravindra babu
It's always better to prefer Executorto Thread
even for single thread as below
它总是更好地喜欢执行官到Thread
即使是单线程如下
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(1);
You can use Thread
over Executor
in below scenarios
您可以在以下场景中使用Thread
overExecutor
Your application needs limited thread(s) and business logic is simple
If simple multi-threading model caters your requirement without Thread Pool
You are confident of managing thread(s) life cycle + exception handling scenarios with help of low level APIs in below areas :
Inter thread communication, Exception handling, reincarnation of threads
due to unexpected errors
您的应用程序需要有限的线程并且业务逻辑很简单
如果简单的多线程模型在没有线程池的情况下满足您的要求
您有信心在以下领域的低级 API 的帮助下管理线程生命周期 + 异常处理场景:
Inter thread communication, Exception handling, reincarnation of threads
由于意外错误
and one last point
最后一点
If your application does not need customization of various features of
ThreadPoolExecutor
ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)
如果您的应用程序不需要自定义各种功能
ThreadPoolExecutor
ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)
In all other cases, you can go for ThreadPoolExecutor
在所有其他情况下,你可以去 ThreadPoolExecutor