三-Spring高级话题(1)-多线程、计划任务-【JavaEE开发的颠覆者】

217 阅读2分钟

一、多线程

Spring通过任务执行器(TaskExecutor)来实现多线程和并发编程。使用ThreadPoolTaskExcutor可实现一个基于线程池的TaskExcutor(任务执行器)。而实际开发中任务一般是非阻碍的,即异步的,所以我们要在配置类中通过@EnableAsync开启对异步任务的支持,并通过在实际执行的Bean的方法中使用@Async注解来声明其是一个异步任务。

1.示例
(1)配置类

//配置类
@Configuration
@ComponentScan("com.zhao.spring.Thread")
@EnableAsync
public class TaskExcutorConfig implements AsyncConfigurer{

    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExcutor=new ThreadPoolTaskExecutor();
        taskExcutor.setCorePoolSize(5);
        taskExcutor.setMaxPoolSize(10);
        taskExcutor.setQueueCapacity(25);
        taskExcutor.initialize();
        return taskExcutor;
    }

    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }
}
/**
 * 使用@EnableAsync注解开启异步任务支持
 * 配置类实现AsyncConfigurer接口并重写getAsyncExcutor方法,并返回一个ThreadPoolTaskExcutor,
 *  这样我们就获得了一个基于线程池TaskExcutor。
 */

(2)任务执行类

//任务执行类
@Service
public class AsyncTaskService {
    @Async
    public void excuteAsyncTask(Integer i){
        System.out.println("执行异步任务:"+i);
    }

    @Async
    public void excuteAsyncTaskPlus(Integer i){
        System.out.println("执行异步任务Plus:"+(i+1));
    }
}
/**
 * 通过@Async注解表明该方法是个异步方法,如果注解在类级别,则表明该类所有的方法都是异步方法
 * 而这里的方法自动被注入使用ThreadPoolTaskExcutor作为TaskExcutor ????
 */

(3)启动类

public class TaskMain {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context=
                new AnnotationConfigApplicationContext(TaskExcutorConfig.class);

        AsyncTaskService asyncTaskService=context.getBean(AsyncTaskService.class);

        for (int i = 0; i < 10; i++) {
            asyncTaskService.excuteAsyncTask(i);
            asyncTaskService.excuteAsyncTaskPlus(i);
        }
        context.close();
    }
}

结果可见是并发执行的而不是顺序执行:
这里写图片描述

二、计划任务

1.从Spring3.1开始,计划任务在Spring中的实现变得异常的简单。首先通过在配置类注解@EnableScheduling来开始对计划任务的支持,然后在要秩序井计划任务的方法上注解@Scheduled,声明这是一个计划任务。
Spring通过@Scheduled支持多种类型的计划任务,包含cron、fixDelay、fixRate等。

2.示例
(1)计划任务执行类

//计划任务执行类
@Service
public class ScheduleService {
    private static final SimpleDateFormat dataFormat=new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000)
    public void scheduleOFfixedRete(){
        System.out.println("使用@Scheduled(fixedRate=5000)注解让方法每5s执行一次:"+dataFormat.format(new Date()));
    }

    @Scheduled(cron = "0 50 10 ? * *")
    public void scheduleOFcron(){
        System.out.println("使用@Scheduled(cron=)注解让方法在指定时间执行:"+dataFormat.format(new Date()));
    }
}
/**
 * 通过@Scheduled声明该方法是计划任务,使用fixedRate属性每隔固定时间执行。
 * 使用cron属性可按照指定时间执行。
 */

(2)配置类

//计划任务配置类
@Configuration
@ComponentScan("com.zhao.spring.Schedule")
@EnableScheduling
public class ScheduleConfig {

}
/**
 *通过@EnableScheduling注解开启对计划任务的支持 
 */

(3)启动

public class ScheduleMain {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context=
                new AnnotationConfigApplicationContext(ScheduleConfig.class);

    }
}

这里写图片描述