1. How to create thread pools
Method (1): Create a thread pool through the constructor ThreadPoolExecutor() method
Step 1: Build the thread pool first
public class AsyncTaskExecutor { /** * Number of core threads */ private static final int corePoolSize = 10; /** * Maximum number of threads */ private static final int maxPoolSize = 30; /** * Idle thread recycling time * Idle thread refers to the number of extra free threads after the current thread pool exceeds the number of core threads. */ private static final int keepAliveTime = 100; /** * Task queue/blocking queue */ private static final int blockingQueueSize = 99999; private static final ThreadPoolExecutor executorPool = new ThreadPoolExecutor( corePoolSize, maxPoolSize, keepAliveTime, , new LinkedBlockingQueue<>(blockingQueueSize), new ThreadFactoryBuilder().setNameFormat("AsyncTaskThread" + "-%d").build(), new () ); /** * Asynchronous task execution * * @param task */ public static void execute(Runnable task) { (task); } }
Step 2: Create asynchronous tasks by implementing the Runnable interface
@Slf4j public class CommonTask implements Runnable { /** * Module ID */ private Long modelId; /** * Module name */ private ModelEnum modelName; /** * Constructing method * * @param modelId * @param modelName */ public CommonTask(Long modelId, ModelEnum modelName) { = modelId; = modelName; } @Override public void run() { ("start to process common task!!!"); if (() == ()) { String name = (); ("modelID = {} modelName = {}", modelId, name); } else { modelName = (()); ("modelID = {} modelName = {}", modelId, ()); } } }
enumerate
public enum ModelEnum { Chinese(1, "Chinese"), Math(2, "math"), English(3, "math"); /** * code */ private int code; /** * value */ private String value; /** * Map result set */ private static final Map<Integer, ModelEnum> VALUE_MAP; static { VALUE_MAP = new HashMap<>(); for (ModelEnum modelEnum : ()) { VALUE_MAP.put(, modelEnum); } } ModelEnum(int code, String value) { = code; = value; } public int getCode() { return code; } public String getValue() { return value; } /** * Get enum instance according to code * * @param code * @return */ public static ModelEnum forValue(int code) { return VALUE_MAP.get(code); } }
Step 3: Verify
//Step 1: Create an asynchronous task CommonTask task = new CommonTask(1L, ); //Step 2: Call the thread pool to execute tasks asynchronously (task); ("main thread over...");
The results are as follows:
2024-05-23 14:53:16.096 INFO 20652 --- [ main] : main thread over...
2024-05-23 14:53:16.097 INFO 20652 --- [yncTaskThread-0] : start to process common task!!!
2024-05-23 14:53:16.097 INFO 20652 --- [yncTaskThread-0] : modelID = 1 modelName = Chinese
Method (2): Build a ThreadPoolTaskExecutor thread pool and declare it as a bean. You can use this thread pool by injecting beans and using @Async("asyncTaskExecutor") on the annotation method.
@Slf4j @Configuration @EnableAsync public class TaskExecutor { @Value("${.core_pool_size}") private int corePoolSize; @Value("${.max_pool_size}") private int maxPoolSize; @Value("${.queue_capacity}") private int queueCapacity; @Value("${.deal_task}") private String taskNamePrefix; /** * Build the thread pool and declare it as a Bean * Method 1: This thread pool can be used by injection * Method 2: You can use this thread pool in annotation method using @Async("asyncTaskExecutor") * * @return */ @Bean(name = "asyncTaskExecutor") public Executor asyncTaskExecutor() { ("start asyncTaskExecutor..."); ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor(); (corePoolSize); (maxPoolSize); (queueCapacity); (taskNamePrefix); //Reject policy: How to handle new tasks after the current number of threads has reached the maximum number of threads //CallerRunsPolicy() does not execute tasks in the new thread, but returns the thread where the caller is located to execute ( new ()); (); return threadPoolTaskExecutor; } }
Configuration in
async: executor: thread: core_pool_size: 10 max_pool_size: 10 queue_capacity: 99999 name: deal_task: DEAL-TASK-
Usage method 1: Use @Async("asyncTaskExecutor") on the method to use this thread pool
Usage method 2: Use this thread pool through injection
@Slf4j @Service public class WorkServiceImpl implements WorkService { @Async("asyncTaskExecutor") public void doAsyncTask() throws InterruptedException { (1000); ("do AsyncTask..."); } }
@Slf4j @RunWith() @SpringBootTest public class UserDaoTest { SqlSession sqlSession; @Resource private WorkService workService; @Resource private Executor asyncTaskExecutor; @Test public void test() { try { //Method 1: Use @Async("asyncTaskExecutor") on the method to use this thread pool for (int i = 0; i < 5; i++) { (); } ("main Thread over..."); //Method 2: Use this thread pool through injection (convenient) (() -> { ("async task is running.."); }); (5000); }catch (Exception e) { (); } } }
This is the end of this article about the summary of the practical application of Java thread pool. For more related Java thread pool content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!