java - SingleThreadExecutor VS 普通线程

标签 java multithreading threadpoolexecutor

除了 Executor 接口(interface)比普通线程有一些优势(例如管理)之外,在做:

ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(runnable);

和:

Thread thread = new Thread(runnable);
thread.start();

我在这里只询问一个线程。

最佳答案

Executors#newSingleThreadExecutor() 在后台创建 ThreadPoolExecutor 对象,
在这里查看代码:http://www.docjar.com/html/api/java/util/concurrent/Executors.java.html

  133       public static ExecutorService newSingleThreadExecutor() {
  134           return new FinalizableDelegatedExecutorService
  135               (new ThreadPoolExecutor(1, 1,
  136                                       0L, TimeUnit.MILLISECONDS,
  137                                       new LinkedBlockingQueue<Runnable>()));
  138       }

documentation of ThreadPoolExecutor解释它在什么情况下会带来优势:

Thread pools address two different problems: they usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead, and they provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks. Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks.

如果你只需要偶尔运行一次单线程(比如每小时一次),那么就性能而言,使用 ThreadPoolExecutor 可能会更慢,因为你需要实例化整个机器(池 + 线程),然后将其从内存中丢弃。

但是如果您想经常使用这个单线程(比如每 15 秒一次),那么优点是您创建池和线程仅一次,将其保存在内存中,然后全部使用时不时地创建一个新线程可以节省时间(如果您想每 15 秒左右使用一次,这可能会非常昂贵)。

关于java - SingleThreadExecutor VS 普通线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50076815/

相关文章:

java - 离开 Activity 时 Android 如何处理后台线程?

java执行器服务

java - 安卓并行(simultaneous)图片下载

java - 当我使用 osgi 包重新启动服务器时 Glassfish 崩溃

java - Vaadin 组合框分隔符

java - 用 Java 编写多线程映射迭代器

c - setcontext 中的段错误

java - JFrame 调用正在打开两个 JFrame

java - Scanner Java 混淆中的定界符

java - ThreadPoolExecutor 中使用 BlockingQueue 的内存使用情况