Java Concurrency: one to get the thread pool

Original Address: https://www.nowcoder.com/discuss/152050?type=0&order=0&pos=6&page=0

This article is in the original foundation + understand that you want the system to learn, look at the original address.

Thread Pools

  1.1 thread pool concept

    Thread Pool (thread pool): in a thread usage patterns. Creating destroying threads is very consumption of resources (memory consumption of thread creation, thread context switching CPU resources from consumption). Use the thread pool can be more fully coordinated application CPU, memory, network, I / O and other system resources. The program starts first create a thread, after the program starts the task can be directly thrown into the thread pool, to perform this task by the thread pool.

  1.2 thread pool to solve problems

    ① thread creation destroy the culprit will open up the virtual machine stack, native method stacks and technical programs and other thread private memory.

    ② If not controlled, the number of threads when it reaches a certain value, because the thread context switching exclusive communication, causes the CPU resources, in extreme cases, the system allocates time slices are used to perform context switches, but no time to perform real tasks.

    ③ create frequent destruction of threads increases the risk of concurrent programming.

    ④ thread pool can solve the wait or pull off friendly service when too many threads.

  1.3 thread pool action

    ① use thread pool thread management multiplexing, control the maximum number of concurrent. (Avoid eat too much, resulting in complete context switch while the real task is not performed)

    ② achieve the task queue thread caching strategies and rejection mechanism. (Processing thread too elegant case)

    ③ achieve certain functions associated with the practice. (You can use the thread pool to complete the scheduled task)

    ④ isolation threaded environment. (Different types of thread pool can put a server, isolate different services, avoiding thread interact)

  1.4 thread pool a little

    ① reduce resource consumption, to avoid frequent memory allocation and destruction

    ② improve the response speed, do not need to complete the creation of threads directly perform tasks (provided that the thread pool idle threads)

    ③ improve the manageability of threads, thread pool can be managed the same way, allocating, monitoring and tuning.

Create a thread pool

    First Custom ThreadFactory and RejectedExecutionHandler from ThreadPoolExecutor construction method is concerned, to write a simple thread pool. By ThreadPoolExecutor of execute and addWorker two core methods.

    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
......
}

  Parameter Description:

    ①corePoolSize: represents the core threads:

        corePoolSize = 0, there is no other task into the thread pool thread will destroy fresh after executing the task

        corePoolSize> 0, the local task is finished, the thread pool thread will remain corePoolSize

    ②maximumPoolSize: represents the number of threads in the pool can accommodate a maximum execution threads

        maximumPoolSize> = 1, if the execution threads in the pool, the number of 1 or greater.

        If you need to perform is greater than the number of threads maximumPoolSize threads, the fifth parameter handler needs to handle, cache or discarded.

    ③keepAliveTime: represents the thread pool thread idle time

        When the idle time reaches keepAliveTime, while the number of threads in the thread pool greater than the number of letter of threads, the thread will be destroyed.

        Using this parameter, you can avoid waste of resources.

        When allowCoreThreadTimeOut = true, the core thread time-out will be recovered.

        From the source, allowCoreThreadTimeOut is modified by the volatile, explain this to say that there are changes in the value of threads in the pool can be seen, because there is no initial value, the default value is false, meaning the core thread time-out will not be recovered.

        It may be set by the process, if set to true, to ensure that the thread is idle time <= 0, that indicates idle immediately recovered.

    private volatile boolean allowCoreThreadTimeOut;
                          
    public void allowCoreThreadTimeOut(boolean value) {
        if (value && keepAliveTime <= 0)
            throw new IllegalArgumentException("Core threads must have nonzero keep alive times");

        allowCoreThreadTimeOut = value;
    }

    ④unit: one unit of time

        keepAliveTime units usually TimeUnit.SECONDS. 

    ⑤workQueue: represents the buffer queue

        When the number of threads requested is greater than the maximum number of concurrent threads, the thread will enter this blockingQueue, obstructive guarantee the atomicity of a team into the team

    ⑥threadFactory: a thread factory

        Used to produce the same task a group of threads.

        Naming the thread pool is achieved by the factory to increase the group name prefix.

        VM stack known at the time the analysis is threaded task that thread factory.

    ⑦handler: an object representing refused strategy

        When the thread to be greater than the maximum blocking execution queue, a request can be processed by the policy, a simple current-limiting protection policy model.

      Elegant refused strategies include:        

        Save the database to consume valley fill; then extracted executed in idle thing

        Steering a prompt page

        Print Log

2.1.1 corePoolSize number of kernel threads.

    The number of threads in the thread pool should newspapers, even during idle thread, the thread will be present in the thread pool, set allowCoreThreadTimeOut unless this parameter is false. When the number of threads in the thread pool is less than the number of kernel threads, thread pool creates a new thread to perform this task, even if there is a free thread pool thread will create a new thread. Such as the number of threads in the thread pool is equal to the number of threads confidence, then will not produce thread, the task will be placed in a queue.

    If whine thread pool prestartAllCoreThreads (), the thread pool will be created in advance and start all core threads.

    public int prestartAllCoreThreads() {
        int n = 0;
        while (addIfUnderCorePoolSize(null))
            ++n;
        return n;
    }

2.1.2 maximumPoolsize thread pool maximum number of threads simultaneously executing threads

    The maximum number of threads in the thread pool allows the creation of

    If the queue is full, and the number of threads that have been created less than the maximum number (fixed number of threads) thread, the thread pool will re-create a new thread into the works to perform tasks. Unbounded queue parameters useless. cachedThreadPool invalid.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/dc-earl/p/11122370.html