SingleThreadExecutor VS plain thread

前端 未结 4 1849
盖世英雄少女心
盖世英雄少女心 2021-02-11 19:08

Apart from the fact that the Executor interface has some advantages over plain threads (management, for example), is there any real internal difference (big perform

4条回答
  •  野的像风
    2021-02-11 20:08

    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()));
      138       }
    

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

    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.

    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.

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

提交回复
热议问题