1

我使用了这个教程它是 github 项目作为这个 SSCCE 的基础。

由于未知原因,标记为@Async从方法运行的@Scheduled方法总是同步执行。

我正在寻找修复或解决方法以使代码performTask()异步运行。

下面的类:

应用程序.java

@SpringBootApplication
@EnableScheduling
@EnableAsync
public class Application implements AsyncConfigurer{

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class);
    }

    @Override
    @Bean(name="asyncExecutor")
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor exec = new ThreadPoolTaskExecutor();
        exec.setMaxPoolSize(Runtime.getRuntime().availableProcessors()*2);
        exec.setThreadGroupName("MyCustomExecutor");
        exec.setWaitForTasksToCompleteOnShutdown(true);
        exec.setBeanName("asyncExecutor");
        exec.initialize();
        return exec;
    }

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

MyAsyncService.java

@Service
public class MyAsyncService {

    static AtomicInteger taskNoCounter = new AtomicInteger();

    public MyAsyncService() {
    }

    @Async("asyncExecutor")
    public void performTask() {
        int delayMs = (int) (System.currentTimeMillis()%1000+1000);
        int taskNo = taskNoCounter.incrementAndGet();
        String taskInfo = "MyAsyncTask [taskNo=" + taskNo + ", delayMs=" + delayMs + ", threadId="+Thread.currentThread().getId()+"]";
        System.out.println("+ start " +taskInfo);
        try {
            Thread.sleep(delayMs);
        } catch (InterruptedException e) {
            // empty on purpose
        }
        System.out.println("- end   " +taskInfo);
    }

}

计划任务.java

@Component
public class ScheduledTasks {

    @Autowired
    MyAsyncService service;

    @Scheduled(fixedRate = 1000)
    public void reportCurrentTime() {
        for (int i=0; i<20; i++) {
            service.performTask();
        }

    }
}

产生以下同步结果:

+ start MyAsyncTask [taskNo=1, delayMs=1874, threadId=16]
- end   MyAsyncTask [taskNo=1, delayMs=1874, threadId=16]
+ start MyAsyncTask [taskNo=2, delayMs=1749, threadId=16]
- end   MyAsyncTask [taskNo=2, delayMs=1749, threadId=16]
+ start MyAsyncTask [taskNo=3, delayMs=1498, threadId=16]
- end   MyAsyncTask [taskNo=3, delayMs=1498, threadId=16]
+ start MyAsyncTask [taskNo=4, delayMs=1997, threadId=16]
- end   MyAsyncTask [taskNo=4, delayMs=1997, threadId=16]
+ start MyAsyncTask [taskNo=5, delayMs=1994, threadId=16]
4

1 回答 1

0

问题不在于corePoolSize设置ThreadPoolTaskExecutor.

默认情况下corePoolSize1只有当队列已满时线程数量才会增加。由于我的队列是无限的,因此池中没有创建任何其他线程。

我最终做了:

exec.setCorePoolSize(Runtime.getRuntime().availableProcessors()+1);
于 2016-02-24T13:16:00.523 回答