Java Concurrent Programming (08): executor thread pool framework

Source code of this article: GitHub · click here | gitee · click here

1、 Introduction to executor framework

1. Basic introduction

The executor system is designed to understand the coupling between thread task submission and task execution. The executor has various powerful implementation classes, which provide a convenient way to submit tasks and obtain task execution results. It encapsulates the process of task execution and no longer needs thread () Start() method, explicitly create a thread and associate execution tasks.

2. Scheduling model

The thread is mapped one-to-one to the operating system thread where the service is located. An operating system thread will be created when starting; When the thread terminates, the operating system thread is also recycled.

3. Core API structure

The core interfaces and main implementation classes contained in the executor framework are shown in the following figure:

Thread pool task: core interfaces: runnable, callable interfaces and interface implementation classes;

Results of the task: interface future and implementation class futuretask;

Task execution: core interface executor and executorservice interface. In the executor framework, two core classes implement the executorservice interface, ThreadPoolExecutor and scheduledthreadpoolexecutor.

2、 Usage cases

1. API Foundation

ThreadPoolExecutor infrastructure

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

2. Initialization method

ExecutorService :Executors.newFixedThreadPool();
ExecutorService :Executors.newSingleThreadExecutor();
ExecutorService :Executors.newCachedThreadPool();

ThreadPoolExecutor :new ThreadPoolExecutor() ;

Generally, thread pools are not allowed to be created using executors, but through ThreadPoolExecutor. This processing method makes the running rules of thread pools clearer and avoids the risk of resource depletion.

3. Basic case

package com.multy.thread.block08executor;
import java.util.concurrent.*;

public class Executor01 {
    // 定义线程池
    private static ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
                    3,10,5000,TimeUnit.SECONDS,new SynchronousQueue<>(),Executors.defaultThreadFactory(),new ExeHandler());
    public static void main(String[] args) {
        for (int i = 0 ; i < 100 ; i++){
            poolExecutor.execute(new PoolTask(i));
            //带返回值:poolExecutor.submit(new PoolTask(i));
        }
    }
}
// 定义线程池任务
class PoolTask implements Runnable {

    private int numParam;

    public PoolTask (int numParam) {
        this.numParam = numParam;
    }
    @Override
    public void run() {
        try {
            System.out.println("PoolTask "+ numParam+" begin...");
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public int getNumparam() {
        return numParam;
    }
    public void setNumParam(int numParam) {
        this.numParam = numParam;
    }
}
// 定义异常处理
class ExeHandler implements RejectedExecutionHandler {
    @Override
    public void rejectedExecution(Runnable runnable,ThreadPoolExecutor executor) {
        System.out.println("ExeHandler "+executor.getCorePoolSize());
        executor.shutdown();
    }
}

Process analysis

3、 Thread pool application

Application scenario: the verification task of batch accounts and passwords is quite common in actual business. By initializing the thread pool, submit the task for execution, and finally get the processing results, this is the core idea of the use of thread pool: save resources and improve efficiency.

public class Executor02 {

    public static void main(String[] args) {
        // 初始化校验任务
        List<CheckTask> checkTaskList = new ArrayList<>() ;
        initList(checkTaskList);
        // 定义线程池
        ExecutorService executorService ;
        if (checkTaskList.size() < 10){
            executorService = Executors.newFixedThreadPool(checkTaskList.size());
        }else{
            executorService = Executors.newFixedThreadPool(10);
        }
        // 批量处理
        List<Future<Boolean>> results = new ArrayList<>() ;
        try {
            results = executorService.invokeAll(checkTaskList);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        // 查看结果
        for (Future<Boolean> result : results){
            try {
                System.out.println(result.get());
                // System.out.println(result.get(10000,TimeUnit.SECONDS));
            } catch (Exception e) {
                e.printStackTrace() ;
            }
        }
        // 关闭线程池
        executorService.shutdownNow();
    }

    private static void initList (List<CheckTask> checkTaskList){
        checkTaskList.add(new CheckTask("root","123")) ;
        checkTaskList.add(new CheckTask("root1","1234")) ;
        checkTaskList.add(new CheckTask("root2","1235")) ;
    }
}
// 校验任务
class CheckTask implements Callable<Boolean> {
    private String userName ;
    private String passWord ;
    public CheckTask(String userName,String passWord) {
        this.userName = userName;
        this.passWord = passWord;
    }
    @Override
    public Boolean call() throws Exception {
        // 校验账户+密码
        if (userName.equals("root") && passWord.equals("123")){
            return Boolean.TRUE ;
        }
        return Boolean.FALSE ;
    }
}

Thread pool is mainly used to solve the problem of thread life cycle overhead and insufficient resources. Multiple task threads are reused through thread pool, and thread creation is also allocated to multiple tasks. Most task submissions have idle threads to use, so the overhead caused by frequent thread creation is eliminated.

4、 Source code address

GitHub·地址
https://github.com/cicadasmile/java-base-parent
GitEE·地址
https://gitee.com/cicadasmile/java-base-parent

Recommended reading: Java Concurrent Programming

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>