Spring Schedule未运行多线程

时间:2018-12-13 20:00:24

标签: java spring-mvc spring-boot spring-scheduled

我在日程表类中有两个异步任务,分别是testAsyncTask1()和testAsyncTask2()。线程卡在testAsyncTask1()的while(true)中,因此无法执行testAsyncTask2()。如何将testAsyncTask1()和testAsyncTask2()运行到多个线程中以避免上述情况?

时间表课程

@Configuration
@EnableAsync
@EnableScheduling
public class Schedule extends AbstractSchedule {

    @Async
    @Scheduled(cron = ScheduleTime.EVERY_10SECONDS, zone = TimeZone.PST)
    public void testAsyncTask1() {
        System.out.println("Thread 1");
        logInfo(SCHEDULER_NAME, "Thread 1", " records updated.");
        while (true) {

        }
    }

    @Async
    @Scheduled(cron = ScheduleTime.EVERY_10SECONDS, zone = TimeZone.PST)
    public void testAsyncTask2() {
        System.out.println("Thread 2");
        logInfo(SCHEDULER_NAME, "Thread 2", " records updated.");
    }
}

AbstractBaseSchedule

public abstract class AbstractBaseSchedule extends ScheduleConfig {

}

ScheduleConfig

@Configuration
public class ScheduleConfig implements SchedulingConfigurer {

    private static final int POOL_SIZE = 10;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(POOL_SIZE);
        taskScheduler.initialize();
        taskRegistrar.setTaskScheduler(taskScheduler);
    }
}

1 个答案:

答案 0 :(得分:1)

您需要更改集corePoolSize的默认值为1。为此,您应该在AsyncConfigurer中实现ScheduleConfig。这将帮助您:

@Configuration
@EnableAsync
@EnableScheduling
public class ScheduleConfig implements AsyncConfigurer, SchedulingConfigurer {

    private final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class);

    @Override
    @Bean(name = "taskExecutor")
    public Executor getAsyncExecutor() {
        log.debug("Creating Async Task Executor");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(50);
        executor.setQueueCapacity(10000);
        executor.setThreadNamePrefix("project-Executor-");
        return new ExceptionHandlingAsyncTaskExecutor(executor);
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(scheduledTaskExecutor());
    }

    @Bean
    public Executor scheduledTaskExecutor() {
        return Executors.newScheduledThreadPool(10);
    }
}