JAVA face questions - understanding of the thread pool

Why use the thread pool, it's what are the advantages?

X can be installed the way, look at the use of threads audit computer:

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

Here Insert Picture Description
Previously created a thread is using new Thread (); method. 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 exceeds the maximum number of threads, beyond the number of threads waiting in line, and other threads finished, then removed from the queue to perform the task.

Main features: thread multiplexing; maximum number of concurrent control; managing threads.

Advantages:
First, reduce resource consumption. To reduce thread creation and destruction caused by the consumption by reusing threads that have been created.
Second, improve the speed accordingly, when the mission arrives, the task may not need to wait until the thread creation can be implemented immediately.
Third, improve the manageability of the thread, the 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.

Analysis of the underlying thread pool

Java threads in the pool is achieved by Executor framework, we used the Executor, Executors, ExecutorService this framework, ThreadPoolExecutor class.

The underlying architecture

Here Insert Picture Description

Coding

To understanding:

  1. Executors.newScheduledThreadPool()
  2. java8 new out Executors.newWorkStealingPool (int)
    more than two can be seen, you do not need in-depth. In the interview he does not need to say when there are five achieve, just say there are three on it.

Key:

  1. Executors.newFixedThreadPool (int) --------------- fixed number of thread pool

Applicable scene: the implementation of long-term task, much better performance

  1. Executors.newSingleThreadExecutor () ---------------- only one thread of the thread pool

Applicable scene: Scene of a task a task execution

  1. Executors.newCachedThreadPool () ----------------- scaleable multi-threaded with a pool of cache

Applicable scene: a lot of short-term asynchronous execution of applets or lightly loaded server

public class MyThreadPoolDemo {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(5);//一池五个处理线程
        ExecutorService threadPool = Executors.newSingleThreadExecutor();//一池一线程
 		ExecutorService threadPool = Executors.newCachedThreadPool();//一池多线程

        //模拟10个用户来办理业务,每个用户就是一个来自外部的请求线程
        try{
            for (int i = 0; i < 10; i++) {
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"\t办理业务");
                });
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            threadPool.shutdown();
        }
    }
}

Source and seven parameters (five parameters)

 public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }
 public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }
public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

We can see from the source code, to achieve three important are new ThreadPoolExecutor, and the last five parameters are related to the blocking queue. And then submit to ThreadPoolExecutor source, we found a total of seven parameters.

public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler)
parameter effect
corePoolSize The core thread pool size
maximumPoolSize Maximum thread pool size
keepAliveTime CorePoolSize thread pool exceeds the number of idle threads maximum survival time; you can allowCoreThreadTimeOut (true) so that the effective time of the core thread
unit keepAliveTime time unit
workQueue Blocking task queue
threadFactory New thread factory
handler When submitting a number of tasks exceeds maxmumPoolSize + workQueue sum, the task will be to deal with RejectedExecutionHandler

Details see seven parameters of the thread pool

The underlying principle

Here Insert Picture DescriptionHere Insert Picture Description
Here Insert Picture Description

Published 10 original articles · won praise 0 · Views 139

Guess you like

Origin blog.csdn.net/qq_33805483/article/details/104099510