当前位置:网站首页>Multithreaded @ async thread pool

Multithreaded @ async thread pool

2022-04-23 16:50:00 Kramer_ one hundred and forty-nine

ThreadPoolExecutor

ThreadPoolExecutor yes JDK Native thread pool
Reference article

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

  • corePoolSize
    Number of core threads
  • maximumPoolSize
    Maximum number of threads
  • keepAliveTime
    The maximum number of threads that can survive , Is the maximum time that can be reserved in the thread pool except for the core thread , Because in the process pool , Except for the core thread, it cannot be cleared even when there is no task , The rest have survival time , It means the longest idle time that a non core thread can keep
  • unit
    Calculation keepAliveTime The unit of
  • workQueue
    Blocking ( wait for ) queue . Altogether ArrayBlockingQueue、LinkedBlockingQueue、SynchronousQueue etc. 7 Blocking queue
  • threadFactory
    A factory for creating threads , Mainly used to create threads , The default is normal priority 、 Non-daemon thread .
  • handler
    Refusal strategy . There are four kinds :
    • AbortPolicy
      Do not perform new tasks , Throw an exception directly , Indicates that the thread pool is full
    • DisCardPolicy
      Do not perform new tasks , Don't throw an exception
    • DisCardOldSetPolicy
      Replace the first task in the message queue with the current new task execution
    • CallerRunsPolicy
      Call directly execute To perform the current task

Example :

public class ThreadPoolTest {
    
    public static void main(String[] args) {
    
        ExecutorService executorService = new ThreadPoolExecutor(3,5,1L, TimeUnit.SECONDS,new ArrayBlockingQueue(4),Executors.defaultThreadFactory());
        for(int i=0;i<7;i++){
    
            executorService.execute(()->{
    
                System.out.println(Thread.currentThread().getName()+" "+"---> Handle the business ");
            });
        }
        executorService.shutdown();
    }
}

Spring ThreadPoolTaskExecutor

Reference article

Example

Add on asynchronous method @Async annotation , And then you need to @SpringBootApplication Start class or @Configuration Annotation class adding annotations @EnableAsync Start multithreading annotation ,@Async Asynchronous multithreading will be started for the marked method , Be careful , The class of this method must be handed over to Spring Container to manage

The configuration file application.properties

#  Number of core thread pools 
spring.task.execution.pool.core-size=5
#  Maximum number of thread pools 
spring.task.execution.pool.max-size=10
#  The capacity of the task queue 
spring.task.execution.pool.queue-capacity=5
#  Lifetime of non core threads 
spring.task.execution.pool.keep-alive=60
#  Prefix name of thread pool 
spring.task.execution.thread-name-prefix=god-jiang-task-

Configuration class AsyncScheduledTaskConfig.java

@Configuration
public class AsyncScheduledTaskConfig {
    

    @Value("${spring.task.execution.pool.core-size}")
    private int corePoolSize;
    @Value("${spring.task.execution.pool.max-size}")
    private int maxPoolSize;
    @Value("${spring.task.execution.pool.queue-capacity}")
    private int queueCapacity;
    @Value("${spring.task.execution.thread-name-prefix}")
    private String namePrefix;
    @Value("${spring.task.execution.pool.keep-alive}")
    private int keepAliveSeconds;
    @Bean
    public Executor myAsync() {
    
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // Maximum number of threads 
        executor.setMaxPoolSize(maxPoolSize);
        // Number of core threads 
        executor.setCorePoolSize(corePoolSize);
        // The size of the task queue 
        executor.setQueueCapacity(queueCapacity);
        // Thread prefix name 
        executor.setThreadNamePrefix(namePrefix);
        // Thread lifetime 
        executor.setKeepAliveSeconds(keepAliveSeconds);

        /** *  Refuse to deal with the strategy  * CallerRunsPolicy(): Let the caller thread run , such as  main  Threads . * AbortPolicy(): Throw an exception directly . * DiscardPolicy(): Direct discarding . * DiscardOldestPolicy(): Discard the oldest task in the queue . */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        // Thread initialization 
        executor.initialize();
        return executor;
    }
}

Service

@Component
@EnableAsync
public class ScheduleTask {
    

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Async("myAsync")
    @Scheduled(fixedRate = 2000)
    public void testScheduleTask() {
    
        try {
    
            Thread.sleep(6000);
            System.out.println("Spring1 Native thread pool " + Thread.currentThread().getName() + "-" + sdf.format(new Date()));
        } catch (InterruptedException e) {
    
            e.printStackTrace();
        }
    }

    @Async("myAsync")
    @Scheduled(cron = "*/2 * * * * ?")
    public void testAsyn() {
    
        try {
    
            Thread.sleep(1000);
            System.out.println("Spring2 Native thread pool " + Thread.currentThread().getName() + "-" + sdf.format(new Date()));
        } catch (Exception ex) {
    
            ex.printStackTrace();
        }
    }
}

版权声明
本文为[Kramer_ one hundred and forty-nine]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231359460728.html