什么时候应该在执行器上使用Java的线程?

时间:2021-08-23 00:19:18

Executor seems like a clean abstraction. When would you want to use Thread directly rather than rely on the more robust executor?

执行者似乎是一个清晰的抽象概念。什么时候您希望直接使用线程而不是依赖于更健壮的执行程序?

7 个解决方案

#1


30  

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.

为了提供一些历史记录,在java 1.5中只添加了执行程序作为java标准的一部分。因此,在某些方面,执行者可以被视为处理可运行任务的更好的新抽象。

A bit of an over-simplification coming... - Executors are threads done right so use them in preference.

有点过于简单化了……-执行器是正确的线程,所以要优先使用它们。

#2


7  

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.

当我需要一些基于拉的消息处理时,我使用线程。例如,队列是在一个单独的线程中循环的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)接口具有更大的潜力,因为您可以使用Executor在Java 5+或j.u中选择一个行为:调度的、优先级的、缓存的等等。c支持Java 1.4。

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.

executor框架具有对崩溃的runnables的保护,并自动重新创建工作线程。在我看来,一个缺点是必须在退出应用程序之前显式地关闭()并等待终止()它们——这在GUI应用程序中不是那么容易。如果使用有界队列,则需要指定RejectedExecutionHandler或新的runnables。

You might have a look at Brian Goetz et al: Java Concurrency in Practice (2006)

您可能会了解Brian Goetz等人:实践中的Java并发(2006)

#3


5  

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.

使用原始线程没有好处。您总是可以向执行程序提供线程工厂,因此即使是自定义线程创建的选项也被包含在内。

#4


3  

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.

除非您需要在线程本身中没有找到更具体的行为,否则您不会使用线程。然后扩展线程并添加特定需要的行为。

Else just use Runnable or Executor.

否则只使用Runnable或Executor。

#5


3  

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...

线程和执行器是不同的工具,用于不同的场景…正如我看到的,就像问为什么我可以使用HashMap时使用ArrayList ?他们是不同的…

#6


3  

java.util.concurrent package provides executor interface and can be used to created thread.

java.util。并发包提供了executor接口,可以用于创建线程。

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是一个可运行的对象,e是一个可以替换的执行对象

(new Thread(r)).start();

(新线程(r)).start();

with

e.execute(r);

e.execute(r);

Refer here

请参考这里

#7


2  

It's always better to prefer Executor to Thread even for single thread as below

最好选择Executor而不是线程,即使是单线程也是如此,如下所示

ExecutorService fixedThreadPool = Executors.newFixedThreadPool(1);

You can use Thread over Executor in below scenarios

您可以在以下场景中使用线程/执行程序

  1. Your application needs limited thread(s) and business logic is simple

    应用程序需要有限的线程,业务逻辑也很简单

  2. If simple multi-threading model caters your requirement without Thread Pool

    如果简单的多线程模型满足您的需求,而没有线程池

  3. 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:线程间通信、异常处理、意外错误导致的线程转世

and one last point

和最后一个点

  1. If your application does not need customization of various features of ThreadPoolExecutor

    如果应用程序不需要定制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

#1


30  

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.

为了提供一些历史记录,在java 1.5中只添加了执行程序作为java标准的一部分。因此,在某些方面,执行者可以被视为处理可运行任务的更好的新抽象。

A bit of an over-simplification coming... - Executors are threads done right so use them in preference.

有点过于简单化了……-执行器是正确的线程,所以要优先使用它们。

#2


7  

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.

当我需要一些基于拉的消息处理时,我使用线程。例如,队列是在一个单独的线程中循环的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)接口具有更大的潜力,因为您可以使用Executor在Java 5+或j.u中选择一个行为:调度的、优先级的、缓存的等等。c支持Java 1.4。

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.

executor框架具有对崩溃的runnables的保护,并自动重新创建工作线程。在我看来,一个缺点是必须在退出应用程序之前显式地关闭()并等待终止()它们——这在GUI应用程序中不是那么容易。如果使用有界队列,则需要指定RejectedExecutionHandler或新的runnables。

You might have a look at Brian Goetz et al: Java Concurrency in Practice (2006)

您可能会了解Brian Goetz等人:实践中的Java并发(2006)

#3


5  

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.

使用原始线程没有好处。您总是可以向执行程序提供线程工厂,因此即使是自定义线程创建的选项也被包含在内。

#4


3  

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.

除非您需要在线程本身中没有找到更具体的行为,否则您不会使用线程。然后扩展线程并添加特定需要的行为。

Else just use Runnable or Executor.

否则只使用Runnable或Executor。

#5


3  

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...

线程和执行器是不同的工具,用于不同的场景…正如我看到的,就像问为什么我可以使用HashMap时使用ArrayList ?他们是不同的…

#6


3  

java.util.concurrent package provides executor interface and can be used to created thread.

java.util。并发包提供了executor接口,可以用于创建线程。

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是一个可运行的对象,e是一个可以替换的执行对象

(new Thread(r)).start();

(新线程(r)).start();

with

e.execute(r);

e.execute(r);

Refer here

请参考这里

#7


2  

It's always better to prefer Executor to Thread even for single thread as below

最好选择Executor而不是线程,即使是单线程也是如此,如下所示

ExecutorService fixedThreadPool = Executors.newFixedThreadPool(1);

You can use Thread over Executor in below scenarios

您可以在以下场景中使用线程/执行程序

  1. Your application needs limited thread(s) and business logic is simple

    应用程序需要有限的线程,业务逻辑也很简单

  2. If simple multi-threading model caters your requirement without Thread Pool

    如果简单的多线程模型满足您的需求,而没有线程池

  3. 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:线程间通信、异常处理、意外错误导致的线程转世

and one last point

和最后一个点

  1. If your application does not need customization of various features of ThreadPoolExecutor

    如果应用程序不需要定制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