SingleThreadExecutor VS 普通线程 [英] SingleThreadExecutor VS plain thread

查看:94
本文介绍了SingleThreadExecutor VS 普通线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了 Executor 接口比普通线程(例如管理)有一些优势外,两者之间是否存在真正的内部差异(巨大的性能差异,资源消耗......):

Apart from the fact that the Executor interface has some advantages over plain threads (management, for example), is there any real internal difference (big performance difference, resource consumption...) between doing:

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

还有:

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

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

I'm only asking about a single thread here.

推荐答案

Executors#newSingleThreadExecutor() 在幕后创建 ThreadPoolExecutor 对象,
请参阅此处的代码:http://www.docjar.com/html/api/java/util/concurrent/Executors.java.html

Executors#newSingleThreadExecutor() creates ThreadPoolExecutor object under the hood,
see the code here: 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       }

ThreadPoolExecutor 文档解释了它在哪些情况下具有优势:

The documentation of ThreadPoolExecutor explains in what situations it gives advantages:

线程池解决两个不同的问题:它们通常提供执行大量异步时提高性能任务,由于减少了每个任务的调用开销,并且它们提供了限制和管理资源的方法,包括线程,在执行任务集合时消耗.每个 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 可能会更慢,因为你需要实例化整个机器(池+线程),然后将其从内存中扔掉.

If all you need is to just run single thread only once in a while (say once an hour), then in terms of performance, using ThreadPoolExecutor may be slower, since you need to instantiate the whole machinery (pool + thread), then throw it away from memory.

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

But if you want to use this single thread often (say every 15 seconds), then the advantage is that you create the pool and thread only once, keeping it in memory, and use it all the time saving time creating a new thread every now and then (which might be quite expensive, if you want to use it say every 15 seconds or so).

这篇关于SingleThreadExecutor VS 普通线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆