Spring高級運用之淺析多線程與計劃任務

Spring對多線程的支持:
Spring通過任務調度器(TaskExecutor)來實現多線程和併發編程,使用ThreadPoolTaskExecutor可以實現一個基於線程池的TaskExecutor。而在實際開發中任務一般是非阻礙的,即異步的,所以我們要在配置類中通過@EnableAsync開啓對異步任務的支持,並且通過在實際開發執行的Bean的方法中使用@Async註解來聲明其是一個異步任務。
創建配置類:

@Configuration
@ComponentScan("com.fuyunwang.taskexecutor")
@EnableAsync    //開啓異步任務的支持
public class TaskExecutorConfig implements AsyncConfigurer {

    //得到基於線程池的TaskExecutor
    public Executor getAsyncExecutor() {

        ThreadPoolTaskExecutor taskExecutor=new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(5);
        taskExecutor.setMaxPoolSize(10);
        taskExecutor.setQueueCapacity(25);
        taskExecutor.initialize();
        return taskExecutor;

    }

}

創建實體類:

@Service
public class AsyncTaskService {

    @Async//標記指定的方法是個異步方法
    public void executeAsyncTask(Integer i){
        System.out.println("異步執行任務:"+i);
    }

    @Async
    public void executeAsyncTaskPlus(Integer i){
        System.out.println("異步執行任務+1:"+(i+1));
    }

}

創建測試類

public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(TaskExecutorConfig.class);
        AsyncTaskService service=context.getBean(AsyncTaskService.class);
        for(int i=0;i<10;i++){
            service.executeAsyncTask(i);
            service.executeAsyncTaskPlus(i);
        }
        context.close();
    }
}

Spring對於計劃任務的支持:
從Spring3.1開始,計劃任務在Spring中的實現變得異常的簡單。首先通過在配置類上註解@EnableScheduling來開啓對於計劃任務的支持,然後在要執行的計劃任務的方法上提供@Scheduled的註解,聲明這個是計劃任務
定義配置類:

@Configuration
@ComponentScan("com.fuyunwang.scheduler")
@EnableScheduling
public class TaskSchedulerConfig {

}

定義計劃任務類:

@Service
public class ScheduledTaskService {
    private static final SimpleDateFormat dateFormat=new SimpleDateFormat("HH:mm:ss");
    @Scheduled(fixedRate=5000)          //通過Scheduled來聲明這個方法是計劃任務,fixedRate屬性指定每隔固定的時間執行指定的方法
    public void reportCurrentTime(){
        System.out.println("每隔5秒執行一次:"+dateFormat.format(new Date()));
    }

    @Scheduled(cron="0 28 11 ? * *")    //cron屬性是按照指定的事件執行,cron是UNIX和類UNIX系統下的定時任務
    public void fixTimeExecution(){

    }
}

運行:

public class Main {
    public static void main(String[] args) {

        AnnotationConfigApplicationContext configApplicationContext=new AnnotationConfigApplicationContext(TaskSchedulerConfig.class);

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章