Four concurrent programming notes: Discussion thread pool java

More content there are omissions, there are questions welcome

table of Contents

  1. What is the thread pool
  2. JDK support for thread pool
  3. Achieve thread pool
  4. Rejection policy
  5. to sum up

What is the thread pool

We talked about java on a thread, in the actual project application, if only for thread creation and use, it may cause the following three questions:

  1. CPU-intensive
  2. Creating and destroying threads for too long
  3. Take up a lot of memory

So we need to be regulated to thread them, while the control thread tool called thread pool. Simply put, the role is to create a thread pool thread becomes idle obtained from the thread pool, close the thread into a return to the thread pool thread.

JDK support for thread pool

In the JDK, it provides a framework Executor in java.util.concurrent package, wherein ThreadPoolExecutor represents a thread pool. Executors class thread pool is playing the role of the factory, you can get a thread pool has a specific function by Executors, ThreadPoolExecutor class implements Executor interface, through this interface, any object can be ThreadPoolExecurot Runnable thread pool scheduling.

Among them, the factory method are the following:

  • newFixedThreadPool (), which returns a fixed number of thread pool. The number of threads in the pool of the thread is always the same, when a new job submission, if the thread pool idle threads, then immediately executed, and if not, then the new task will be temporarily stored to a task queue with idle a thread is, then processing tasks task queue.
  • newFixedThreadPool (), which returns a single embodiment of the thread pool.
  • newCachedThreadPool (), which returns a number of threads can be adjusted according to the actual situation of the thread pool. Due to an unspecified number of threads, when there is idle threads, the thread can be reused, if all the threads are at work, another new task submission, new thread processing task is created.

Below newFixedThreadPool (), for example, using a simple method to show the thread pool:

public class ThreadPoolTest {
    public static void main(String[] args) {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello World");
            }
        });
        //创建线程池
        ExecutorService es  = Executors.newFixedThreadPool(5);
        for(int i=0;i<10;i++){
            es.submit(t);
        }
        //关闭线程池
        es.shutdown();
    }
}

Achieve thread pool

Whether it is the thread pool newFixedThreadPool (), newFixedThreadPool () or newCachedThreadPool (), which are used inside the same class ThreadPooleExecuor to newFixedThreadPool () as an example:

 

public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>(),
                                  threadFactory);
}

ThreadPooleExecuor class constructor is:

public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue) {
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
         Executors.defaultThreadFactory(), defaultHandler);
}

Constructor parameters defined as follows:

  • corePoolSize: specifies the number of threads in the pool;
  • maximumPoolSize: develop a maximum number of threads in the thread pool;
  • keepAliveTime: When the number of thread pool threads exceeds corePoolSize, excess idle threads of survival time, or more than corePoolSize idle thread will be destroyed for how long;
  • unit: the unit keepAliveTime;
  • workQueue: task queue, but the task has not yet been submitted to be executed;
  • threadFactory: thread factory used to create a thread, you can usually use the default;
  • handler: deny policy, when too much time to deal with the task, how to refuse the task;

Rejection policy

  • AbortPolicy Strategy: The strategy will direct throw an exception, preventing the system from working properly
  • CallerRunsPolicy strategy: as long as the thread pool is not closed, the policy directly in the caller's thread running current task is discarded, it is clear that this does not really discard task, however, the performance of job submission thread is likely to be a sharp decline
  • DiscardOldestPolicy strategy: This strategy will discard the oldest one request, that is a task to be executed, and try to re-submit the current job
  • DiscardPolicy strategy: This strategy can not handle the task silently discarded, without any treatment

to sum up

Above explained the role of the thread pool, thread pool to achieve the case and a simple thread pool implementation logic. The next chapter, we will talk about concurrent containers jdk, so stay tuned ~

Published 60 original articles · won praise 57 · views 80000 +

Guess you like

Origin blog.csdn.net/qixinbruce/article/details/86710631
Recommended