(41) java thread pool and contract types and characteristics described in

Program thread too much can cause performance and stability of the program has fallen, in order to avoid unrestricted create threads, use the thread pool technology.

The number of threads in the thread pool is limited, there is a new task, put the package into a runnable task object to the thread pool thread to execute, execute a thread after completing a task, you can immediately go to the next task .

The number of threads in the pool may be fixed-size, it may be elastically stretchable.

java and contracting:

JDK5.0 later versions have introduced advanced concurrency features, most of the properties in the java.util.concurrent package, is designed for multi-threaded programming, full use of the power of modern multi-processor and multi-core systems to preparation of large-scale concurrent applications. Mainly it contains atomic weight, concurrent collections, synchronizer , reentrant lock, and the structure of the thread pool provides a strong support .

 Thread pool of five kinds created:

 

1, Single Thread Executor: only one thread of the thread pool, so all task execution order is submitted,

代码: Executors.newSingleThreadExecutor()

 

2, Cached Thread Pool: thread pool threads have a lot needs to be performed at the same time, the old threads available to be re-trigger a new task execution, if a thread Chaoguo 60 did not perform seconds, it will be terminated and removed from the pool ,

Code: Executors.newCachedThreadPool ()

 

3, Fixed Thread Pool: have a fixed number of threads in the thread pool, if there is no task execution, the thread will wait,

Code: Executors.newFixedThreadPool (. 4)

Constructor parameter 4 is the size of the thread pool, you can arbitrarily set, and may be cpu of the number of cores consistent cpu obtain the number of cores int cpuNums = Runtime.getRuntime () availableProcessors ( ).;

 

4, Scheduled Thread Pool: used to schedule tasks to be executed in the thread pool may not be directly executed , how often executed once ... strategy type

Code: Executors.newScheduledThreadPool ()

 

5, Single Thread Scheduled Pool: only one thread is used to schedule tasks in the allotted time , the code: Executors.newSingleThreadScheduledExecutor ()

 

Guess you like

Origin www.cnblogs.com/paradis/p/11432945.html