异步任务处理注解方法@Async实现异步多线程

异步任务处理注解方法@Async实现异步多线程

1.定义配置类,设置参数
2.定义任务执行类
3.执行
Spring 中的ThreadPoolExecutor是借助JDK并发包中的java.util.concurrent.ThreadPoolExecutor来实现的。其中一些值的含义如下:
int corePoolSize:线程池维护线程的最小数量
int maximumPoolSize:线程池维护线程的最大数量,线程池中允许的最大线程数,线程池中的当前线程数目不会超过该值。如果队列中任务已满,并且当前线程个数小于maximumPoolSize,那么会创建新的线程来执行任务。
long keepAliveTime:空闲线程的存活时间TimeUnit unit:时间单位,现由纳秒,微秒,毫秒,秒
BlockingQueue workQueue:持有等待执行的任务队列
RejectedExecutionHandler handler 线程池的拒绝策略,是指当任务添加到线程池中被拒绝,而采取的处理措施。

当任务添加到线程池中之所以被拒绝,可能是由于:第一,线程池异常关闭。第二,任务数量超过线程池的最大限制。
Reject策略预定义有四种:
(1)ThreadPoolExecutor.AbortPolicy策略,是默认的策略,处理程序遭到拒绝将抛出运行时 RejectedExecutionException。
(2)ThreadPoolExecutor.CallerRunsPolicy策略 ,调用者的线程会执行该任务,如果执行器已关闭,则丢弃.
(3)ThreadPoolExecutor.DiscardPolicy策略,不能执行的任务将被丢弃.
(4)ThreadPoolExecutor.DiscardOldestPolicy策略,如果执行程序尚未关闭,则位于工作队列头部的任务将被删除,然后重试执行程序(如果再次失败,则重复此过程).

 1.定义配置类,设置参数

package cc.test.config;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@Configuration
@EnableAsync
public class TaskExecutorConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(5);
        taskExecutor.setMaxPoolSize(10);
        taskExecutor.setQueueCapacity(50);
        taskExecutor.initialize();
        return taskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }


}

2.定义任务执行类

package cc.test.service;


import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

/**
 *
 */
@Repository("asyncTaskService")
public class AsyncTaskService {

    @Async
    public void executeAsyncTask1(Integer i){
        System.out.println(Thread.currentThread().getId() + "-" + Thread.currentThread().getName()+"执行异步任务1:"+i);
    }

    @Async
    public void executeAsyncTask2(Integer i){
        System.out.println(Thread.currentThread().getId() + "-" + Thread.currentThread().getName()+"执行异步任务2:"+i);
    }

}

3.执行

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
    @Autowired
    AsyncTaskService asyncTaskService;
    @Test
    public void contextLoads() {
        System.out.println("hello");
        for(int i=0;i<10;i++){
            asyncTaskService.executeAsyncTask1(i);
            asyncTaskService.executeAsyncTask2(i);
        }
    }
}

 

上一篇:Docker6之Network containers


下一篇:SpringBoot配置异步任务(@Async)线程池