Seven ways to create a thread pool

、 、 NewSingleThreadExecutor ()

Its characteristic is that the number of worker threads is limited to 1, operating an unbounded work queue, so it packs that all tasks are executed sequentially, at most one task is active, and users are not allowed to change the thread pool instance , So you can avoid changing the number of thread pools.

二、newFixedThreadPool(int nThread)

It is a thread pool used to process a large number of short-time work tasks. It has several distinctive features.
① It will try to cache threads and reuse them. When no cached threads are available, it will create new worker threads.
② If the thread limit time exceeds 60 seconds, it will be terminated and removed from the cache.
③When idle for a long time, this thread pool will not consume any resources.
It uses ScychronousQueue internally as a work queue

三 、 newCachedThreadPool ()

It is used to create a specified number of threads. Behind it is an unbounded work queue, and up to a specified number of worker threads are active at any time. This means that if the number of tasks exceeds the specified number of active queues, they will always wait for the emergence of idle threads in the work queue; if a worker thread exits, a new worker thread will be created to make up for the specified number of threads

、 、 NewSingleThreadScheduledExecutor ()

Create a single-threaded pool and return to ScheduledExectorService, which can perform regular or periodic work scheduling

五、newScheduledThreadPool()

Similar to newSingleThreadScheduledExecutor(), a ScheduledExectorService is created, which can be scheduled or scheduled periodically. The difference is a single worker thread or multiple worker threads

六、newWorkStealPool(int parallelism)

This creation method was added to Java8, and ForkJoinPool will be built internally, using the Work-Stealing algorithm to process tasks in parallel, and the processing order of the tasks is not guaranteed

七、ThreadExecutorPool()

It is the most primitive thread pool creation. The above 1-3 creation methods are all encapsulation of ThreadExecutorPool()

Guess you like

Origin blog.csdn.net/qq_42697271/article/details/113726770