【Spring】 (8)注解实现多线程

来源:互联网 发布:爱之谷源码 编辑:程序博客网 时间:2024/06/06 09:10
package com.example.demo_3_2;import org.springframework.scheduling.annotation.Async;import org.springframework.stereotype.Service;/** * Created by WangBin on 2017/4/18. * */@Servicepublic class AsyncTaskService {    @Async//通过该注解 表明 该方法是个异步方法如果注解在类级别 则表明 该类所有的方法都是异步方法    // 而这里的方法自动被注入使用 ThreadPoolTaskExecutor 作为TaskExecutor    public void executeAsyncTask(Integer i){        System.err.println("执行异步任务====="+i);    }    @Async    public void executeAsyncTaskPlus(Integer i){        System.err.println("执行异步任务+1====="+(i+1));    }}

package com.example.demo_3_2;import org.springframework.context.annotation.AnnotationConfigApplicationContext;/** * Created by WangBin on 2017/4/18. * */public class Main {    public static void main(String[] args) {        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskExecutorConfig.class);        AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService.class);        for (int i = 0; i < 10; i++) {            asyncTaskService.executeAsyncTask(i);            asyncTaskService.executeAsyncTaskPlus(i);        }        context.close();    }}

package com.example.demo_3_2;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;import java.util.concurrent.ThreadPoolExecutor;/** * Created by WangBin on 2017/4/18. * */@Configuration@ComponentScan("com.example.demo_3_2")@EnableAsync// 使用该注解开启异步任务支持public class TaskExecutorConfig implements AsyncConfigurer{//配置类实现AsyncConfigurer接口 并重写getAsyncExecutor方法    @Override    public Executor getAsyncExecutor() {//返回一个        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();        threadPoolTaskExecutor.setCorePoolSize(5);//核心线程数,核心线程会一直存活,即使没有任务需要处理。当线程数小于核心线程数时,//        即使现有的线程空闲,线程池也会优先创建新线程来处理任务,而不是直接交给现有的线程处理。//        核心线程在allowCoreThreadTimeout被设置为true时会超时退出,默认情况下不会退出。        threadPoolTaskExecutor.setMaxPoolSize(10);//当线程数大于或等于核心线程,且任务队列已满时,线程池会创建新的线程,        // 直到线程数量达到maxPoolSize。如果线程数已等于maxPoolSize,且任务队列已满,则已超出线程池的处理能力,        // 线程池会拒绝处理任务而抛出异常。        threadPoolTaskExecutor.setQueueCapacity(25);//任务队列容量。从maxPoolSize的描述上可以看出,        // 任务队列的容量会影响到线程的变化,因此任务队列的长度也需要恰当的设置。        threadPoolTaskExecutor.initialize();        return threadPoolTaskExecutor;    }    @Override    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {        return null;    }}//keepAliveTime//当线程空闲时间达到keepAliveTime,该线程会退出,直到线程数量等于corePoolSize。// 如果allowCoreThreadTimeout设置为true,则所有线程均会退出直到线程数量为0。//        allowCoreThreadTimeout//        是否允许核心线程空闲退出,默认值为false。