Java multi-threaded 04-- rational use of thread pool

Prior to this, we have a basic knowledge of thread, will bring you today, this thread pool technology. I am concerned about the number of public "side Java Code" to learn more Java-related knowledge.

Why use a thread pool? Thread pool to do the work is mainly to control the number of threads running.

Kind of thread pool

Common thread pool in Java, there are four: newCachedThreadPool , newFixedThreadPool , newScheduledThreadPool , newSingleThreadExecutor .

newCachedThreadPool

Role : Creates a thread pool that can be cached, if the length of the thread pool exceeds the processing needs, the flexibility to recover idle threads ( 缓存中已有 60 秒钟未被使用的线程), if not recoverable, then the new thread.

Features : thread pool is infinite, the first task has been completed when the second task, the thread used to perform the first task will be complex, rather than each time a new thread.

Realization :

ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
    final int index = i;
    try {
        Thread.sleep(index * 1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    cachedThreadPool.execute(new Runnable() {
        @Override
        public void run() {
            System.out.println(index);
        }
    });
}

newFixedThreadPool

Role : to create a fixed-size thread pool, you can control the maximum number of concurrent threads, excess threads will wait in the queue.

Features :

  1. If during the execution before the closure due to a failure of any thread terminates, then replace it with a new thread to execute subsequent tasks (if required);
  2. Before a thread is explicitly closed, the thread pool will always exist.

定长线程池的大小最好根据系统资源进行设置。如Runtime.getRuntime().availableProcessors()。

Realization :

ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
for (int i = 0; i < 10; i++) {
    final int index = i;
    fixedThreadPool.execute(new Runnable() {
        @Override
        public void run() {
            try {
                System.out.println(index);
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
}      

newScheduledThreadPool

Role : to create a fixed-length thread pool to support regular and periodic task execution.

Realization :

ScheduledExecutorService scheduledThreadPoo l= Executors.newScheduledThreadPool(3); 

scheduledThreadPool.schedule(newRunnable() { 
    @Override 
    public void run() {
        System.out.println("延迟三秒");
    }
}, 3, TimeUnit.SECONDS);

scheduledThreadPool.scheduleAtFixedRate(newRunnable(){ 
    @Override 
    public void run() {
        System.out.println("延迟 1 秒后每三秒执行一次");
    }
}, 1, 3, TimeUnit.SECONDS);

newSingleThreadExecutor

Role : to create a single-threaded thread pool, use it only to perform the task only worker threads to ensure that all tasks are performed in a specified order (FIFO, LIFO, priorities).

Features : (or when an exception occurs) in the thread pool thread can restart after the death of a thread to replace the original thread to continue execution.

ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
    final int index = i;
    singleThreadExecutor.execute(new Runnable() {

        @Override
        public void run() {
            try {
                System.out.println(index);
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
}

Principle thread pool

Role : thread multiplexing , control the maximum number of concurrent , thread management . 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 exceeds the number of threads waiting in line, and other threads of execution is completed, and then taken from the queue to perform the task.

Thread multiplexing

Each has a Thread class start () method. When you call start start thread Java Virtual Machine calls the run class () method. Then the class run () method is to call the run () method Runnable object. We can rewrite inherit the Thread class, Runnable object continues to add cycle calls are passed over in its start () method. This is the realization of the principle of the thread pool. The cyclic process with continuous access to Runnable Queue is implemented, before obtaining the next Runnable may be blocked.

The composition of the thread pool

General thread pool is divided into the following four components:

  1. Thread pool manager: to create and manage the thread pool;
  2. Worker threads: threads in the pool;
  3. Task interface: each task must implement the interface for scheduling worker threads that run;
  4. Task Queue: means for storing tasks to be processed to provide a buffering mechanism.

Java threads in the pool is achieved by Executor framework, we used the Executor, Executors, ExecutorService, ThreadPoolExecutor, Callable and Future, FutureTask these classes in the framework. ThreadPoolExecutor configuration as follows:

/**
* @param corePoolSize 指定线程池中的线程数量
* @param maximumPoolSize 指定线程池中的最大线程数量
* @param keepAliveTime 当前线程池数量超过 corePoolSize 时,多余的空闲线程的存活时间
* @param unit keepAliveTime 的单位
* @param workQueue 任务队列,被提交但尚未被执行的任务
*/
public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
    // threadFactory 线程工厂,用于创建线程,一般用默认的即可
    // handler 拒绝策略,当任务太多来不及处理,如何拒绝任务
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), defaultHandler);
}

Rejection policy

Role : thread in the pool is used up, new tasks can not continue to serve, while also waiting queue is already full, never would fit new task. This time we need to reject the policy of reasonable mechanism to deal with this problem.

JDK built-denial strategy is as follows :

  1. AbortPolicy : direct throw, that prevent normal;
  2. CallerRunsPolicy : As long as the thread pool is not closed, the policy directly in the caller's thread, run the current task is discarded. Obviously this does not really discard task, however, the performance of job submission thread is likely to be a sharp decline;
  3. DiscardOldestPolicy : discard the oldest one request, that is a task to be executed, and try to re-submit the current job;
  4. DiscardPolicy : This policy can not handle the task silently discarded, without any treatment. If you allow the task is missing, it is the best kind of program.

More built-denial strategies have achieved RejectedExecutionHandler interfaces, if the above strategy still can not meet the actual needs, you can extend RejectedExecutionHandler interfaces themselves.

Java thread pool worker process

  1. When the thread pool just created, there is no thread. Task queue is passed in as a parameter. However, even if the queue which has the task, the thread pool will not execute them immediately;
  2. When you call the execute () method to add a task, the thread pool will do the following judgment:

a) If the number of threads running less than corePoolSize, then immediately create a thread to run this task;

b) If the number of running threads greater than or equal corePoolSize, then this task in a queue;

c) if this time the queue is full, and the number of threads running less than maximumPoolSize, you still have to
create a non-core thread to run this task immediately;

d) If the queue is full, and the number of threads running greater than or equal to maximumPoolSize, the thread pool will throw an exception RejectExecutionException.

  1. When a thread is to complete the task, it is removed from a queue to perform the task;
  2. When a thread is nothing more than a certain period of time (keepAliveTime), the thread pool will determine if the number of the currently running thread is more than corePoolSize, then the thread is stopped. So after all the tasks of the thread pool is completed, it will eventually shrink to the size of corePoolSize.

Multithreading and concurrency Series Recommended

Java multi-threaded 03-- what is the thread context, how the threads are scheduled

Life Cycle Java multithreading 02-- threads and common methods, you have mastered it

Java multi-threaded 01-- thread creation and termination, you will in several ways

Guess you like

Origin www.cnblogs.com/weechang/p/12527425.html