Common four thread pools and differences

The thread pool can effectively deal with the concurrency problem of multiple threads, avoid the blocking phenomenon caused by a large number of threads occupying system resources for each other, and can effectively reduce the performance overhead caused by the frequent creation and destruction of threads. The implementation of the real thread pool is through ThreadPoolExecutor, which creates thread pools by configuring different parameter configurations. The following briefly introduces the differences and uses of each thread pool.

(1) fixThreadPool regular thread

          My understanding is that this is a thread pool with a specified number of threads, threads with cores, a fixed number of threads in it, and a fast response speed. Regular concurrent threads are mostly used in servers. The fixed number of threads is set by system resources.

   public static ExecutorService newFixedThreadPool(int threads)
    {
    return newFixedThreadPool(threads,threads,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());
    }
There is no timeout mechanism for core threads, and there is no limit to the size of the queue. Unless the thread pool closes the core thread, it will be recycled.

(2) caCheThreadPool cache thread pool

         There are only non-core threads, and the maximum number of threads is very large (Int.Max(values)). It will add a new thread for each task. There is a timeout mechanism here. When the idle threads are not used for more than 60s, will be recycled. The disadvantage is that it does not take into account the actual memory size of the system.

   public static ExecutorService newCachedThreadPool(int threads)
    {
    return newFixedThreadPool(threads,Integer.MAX_VALUE,60L, TimeUnit.SECONDS,new SynchronousQueue<Runnable>());
    }

(3) singleThreadPoll single thread thread pool

 From the name, you can see that this guy has only one core thread, that is, a loner. He throws tasks into threads one by one in a specified order, and they all queue up obediently for execution. Concurrent operations are not processed and will not be recycled. It is certain that a person is slow to work efficiently.

(4)ScheduledThreadPoll   

         This thread pool is amazing, it is the only thread pool with delayed execution and periodic repetition. Its core thread pool is fixed, and the number of non-core threads is unlimited, but it will be reclaimed immediately when idle.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325989918&siteId=291194637