Way to create a thread pool

1.   Single Thread Exector :

  Only one thread of the thread pool, so all submitted tasks are executed sequentially, the key code: Executors.newSingleThreadExecutor ();

2.   Cached Thread Pool :

       Creating a cache thread pool, thread pool longer than if treatment needs, the flexibility to reclaim idle thread, if not recyclable, the new thread.

       This type of thread pool is characterized by:

  The number of worker threads to create a virtually unlimited (in fact, there is a limit, the number is Interger. MAX_VALUE), this can be flexible to add a thread pool thread.

  b If there is no time to submit the task to the thread pool, that is, if the worker thread has been idle for a specified time (default is 1 minute), then the worker thread will automatically terminate. Upon termination, but if you submitted a new task, the thread pool to re-create a worker thread.

  c When using CachedThreadPool, must pay attention to the number of control tasks, otherwise, due to the large number of threads to run simultaneously, great cause system down.

       Key Code: Executors.newCachedThreadPool ();

3.    Fixed ThreadPool :

  Specifies the number of worker threads to create a thread pool. Whenever submit a task to create a worker thread, if the number of worker threads the thread pool reaches the maximum number of initial tasks will be submitted to the pool into the queue.

  FixedThreadPool is a typical and excellent thread pool, which has a thread pool to improve program efficiency and cost-saving advantages when creating the thread consumption.

  However, when the thread pool idle, that is, when the thread pool is not runnable tasks, it will not release the worker, but also take up some system resources.

  Key Code: Executors.newFixedThreadPool (3); constructor parameter is the size of the thread pool 3, can be arbitrarily set, and may be consistent with the number of cpu,

                          Get the number of cpu int cpuNums = Runtime.getRuntime.avaliableProcessors ();

4. Scheduled Thread Pool:

   Used to schedule tasks to be executed in the thread pool to support regular and periodic task execution.

  Key Code: Executors.newScheduledThreadPool ();

5. Sinle Scheduled Thread Pool:

  Only one thread is used to schedule tasks in the allotted time,

  Key Code: Executors.newSingleThreadExecutor () ;;

 

Guess you like

Origin www.cnblogs.com/liu-xiaolong/p/11102137.html