java - 如何对不同的 ExecutorService 对象重用线程?

标签 java concurrency threadpool executorservice

是否可以为我的整个程序设置一个线程池以便重复使用线程,或者我是否需要将 ExecutorService 设为全局/将其传递给所有使用它的对象。

更准确地说,我有多个任务在我的程序中运行,但它们运行的​​频率并不高。

ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);

我认为没有必要让一个完整的线程一直运行每个任务,但每次执行任务时重新启动线程的成本也可能很高。

是否有更好的替代方法来使线程池成为全局线程池?

最佳答案

How do I reuse Threads with different ExecutorService objects?

不可能在不同的 ExecutorService 线程池中重复使用线程。但是,您当然可以将截然不同类型的 Runnable 类提交到一个公共(public)线程池。

Is there a better alternative to making the Thread pool global?

我没有发现您的应用程序中的“全局”线程池存在问题。当然,有人需要知道何时对其调用 shutdown(),但这是我看到的唯一问题。如果您有许多提交任务的不同类,它们都可以访问这组(或 1 组)公共(public)后台线程。

但是您可能会发现,不同的任务可能需要使用缓存的线程池,而其他任务则需要固定大小的池,因此仍然需要多个池。

I believe that it would be unnecessary to have a full thread running all the time for every single task but it might also be costly to restart the thread every single time when a task is executed.

一般来说,除非您要 fork 成吨成吨的线程,否则每隔一段时间启动一个线程的相对成本相对较小。除非您有来自探查器或其他来源的证据,否则这可能是过早的优化。

关于java - 如何对不同的 ExecutorService 对象重用线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18234476/

相关文章:

java - 持久 HashMap 、并发 JDBM

java - 如何避免通过 Java 在数据库中重复插入?

c++ - condition_variable 项不计算为采用 0 个参数的函数

java.lang.IllegalStateException : Fragment has not been attached yet Android Studio

java - 希尔密码加密中的 CBC

java - android.util.Pair 作为 HashMap 中的键

java - 如何将数据传递到线程 System.in 以及如何从线程 System.out 获取数据?

multithreading - 如果我的程序有更多线程,它会获得更多的 CPU 时间吗

c# - TaskCreationOptions.LongRunning 选项和 ThreadPool

java - java客户端应用程序的ms access数据库的锁定机制用于多表更新