java interview - the thread pool used it to talk about the understanding of ThreadPoolExector

 First, the architecture Description:

Second, why use the thread pool, what advantage?

Thread pool to do work is mainly to control the number of threads running, the task will be placed in the queue process, and then start these tasks after thread creation, if the number of threads exceeds the maximum number, then the number of threads waiting beyond, and other the thread is finished, then remove from the queue to perform the task.

Features: Thread multiplexing, control the maximum number of concurrent, thread management

advantage:

  • Reduce resource consumption. To reduce thread creation and destruction caused by the consumption by reusing threads that have been created.
  • Improve the response speed. When the mission arrives, the task may not need to wait until the thread creation can be implemented immediately.
  • Thread improve manageability. A thread is a scarce resource, if the unlimited creation, not only consumes system resources, but also reduce the stability of decency, using threads can be unified distribution, tuning and monitoring.

2, features:

newFixedThreadPool (): implementation of a long-term task, much better performance

newSingleThreadExecutor (): a task to perform a task order

newCachedThreadPool (): used to handle a large number of short-term tasks of the thread pool

Code demonstrates:

{class MyThreadPoolDemo public 
    public static void main (String [] args) { 

// ExecutorService Executors.newFixedThreadPool ExecutorService = (. 5); // time a processing thread 5 
// ExecutorService Executors.newSingleThreadExecutor ExecutorService = (); 
// ExecutorService ExecutorService Executors.newCachedThreadPool = (); 

        // use real project 
        ExecutorService ExecutorService the ThreadPoolExecutor new new = (2,. 3, 1L, TimeUnit.SECONDS, 
                new new a LinkedBlockingQueue <> (. 5), 
                Executors.defaultThreadFactory (), 
                new new ThreadPoolExecutor.DiscardOldestPolicy ()) ; 
        the try { 
            // simulation 10 users to transact business 
            for (int i = 0; i <12; i ++) {

//                try {
//                    TimeUnit.SECONDS.sleep(1);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
                executorService.execute(() -> {
                    System.out.println(Thread.currentThread().getName()+" 办理业务");
                });
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            executorService.shutdown();
        }
    }
}  

三、ThreadPoolExecutor

Fourth, the thread pool parameters introduced seven

corePoolSize: core number of threads in the thread pool

maximumPoolSize: The maximum number of threads in the thread pool, this value must be greater than or equal to 1

keepAliveTime: survival time of excess idle thread , the thread pool exceeds the number of corePoolSize, idle for keepAliveTime value, the excess idle threads will be destroyed until the remaining threads until the corePoolSize

TimeUnit: keepAliveTime units

workQueue: task queue, the task is submitted but has not yet been executed

threadFactory: Set factory creates threads

RejectedExecutionHandler: denial strategy, when the number of tasks submitted more than maxmumPoolSize + workQueue sum, the task will be to deal with RejectedExecutionHandler

Fifth, the principle underlying thread pool

Task 1, after creating a thread pool, waiting for requests submitted over.

2, ThreadPoolExecutor execute execute method, the thread pool will do the following judgment:

  • If the thread is currently running less than corePoolSize, creating a new thread to execute the task (note that the implementation of this step needs to acquire the global lock).
  • If the running thread is equal to or more than corePoolSize, the task will join BlockingQueue.
  • If you can not join the task BlockingQueue (queue is full), then create a new thread to handle the task (note that the implementation of this step needs to acquire the global lock).
  • If you create a new thread currently running thread will exceed maximumPoolSize, the thread pool will enable policy to refuse to perform.

3, when a thread completes the task, a task is removed from the queue will be executed in

4, when the thread is idle for keepAliveTime value, thread pool will determine if the current is greater than the number of threads corePoolSize, then the thread will be stopped.

   So all the tasks after the completion of the thread pool will eventually shrink to the size of corePoolSize.

Six, four kinds of strategies refused thread pool

When the queue and thread pools are full, indicating that the thread pool is saturated, it must adopt a strategy to deal with the new task submitted

  • AbortPolicy (default): Direct RejectedExecutionException throw an exception occurs.
  • CallerRunsPolicy: The policy neither abandon the task, it will not throw an exception, but will fall back to the caller certain tasks, thereby reducing the flow of new tasks
  • DiscardOldestPolicy: discard the queue waiting for the longest task, then the current task to join the queue to try again submit the current job.
  • DiscardPolicy: direct discarded, no treatment does not throw an exception.

Sixth, the actual use of the thread pool work

public class ThreadPoolExecutorDemo {
    public static void main(String[] args) {
        ExecutorService executorService = new ThreadPoolExecutor(2, 3, 1L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(5),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardPolicy());
    }
}  

Sixth, a reasonable number of threads the thread pool configuration

 View the number of cpu core computer:

public class CPUCoresDemo {
    public static void main(String[] args) {
        System.out.println(Runtime.getRuntime().availableProcessors());
    }
}

1, the CPU-intensive: the task requires a lot of computation, without obstruction, CPU runs at full speed.

Less CPU-intensive tasks to configure the number of threads as possible,

Formula: CPU core number + a thread pool thread.

2, IO-intensive: the task requires a lot of IO, that is a lot of obstruction

Since the IO-intensive task thread has not always been on a mission, you can assign a little more than the number of threads, such as CPU * 2.

Using the formula: CPU Audit / (l blockage factor); wherein a blockage factor between 0.8 and 0.9.

  

 

Guess you like

Origin www.cnblogs.com/wjh123/p/11192656.html