記錄遇到的問題springboot使用@Async 注解不生效


今天在使用了線程池,遇到了@Async不生效的問題,具體線程池的代碼如下

@Configuration
@EnableAsync
public class ExecutorConfig {
    private static Logger logger = LogManager.getLogger(ExecutorConfig.class.getName());

    @Bean
    public Executor asyncServiceExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心線程數
        executor.setCorePoolSize(5);
        //配置最大線程數
        executor.setMaxPoolSize(10);
        //配置隊列大小
        executor.setQueueCapacity(400);
        //配置線程池中的線程的名稱前綴
        executor.setThreadNamePrefix("thread-");
        // rejection-policy:當pool已經達到max size的時候,如何處理新任務
        // CALLER_RUNS:不在新線程中執行任務,而是有調用者所在的線程來執行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //執行初始化
        executor.initialize();
        return executor;
    }
}

一開始我將所有的任務都放在了一個方法里,具體代碼如下

 @Override
    @Async("asyncServiceExecutor")
    public void writeTxt(String fileName) {


        System.out.println("線程" + Thread.currentThread().getId() + "開始執行");
        File file = new File("F://F.zip");
        File f2 = new File("F://test");
        File f3 = new File("F://test1");
        File f4 = new File("F://test2");
        long startTime = System.currentTimeMillis();   //獲取開始時間
        try {

            FileUtils.copyFileToDirectory(file, f2);
            FileUtils.copyFileToDirectory(file, f3);
            FileUtils.copyFileToDirectory(file, f4);
            long endTime = System.currentTimeMillis(); //獲取結束時間
            System.out.println("程序運行時間: " + (endTime - startTime) + "ms");
            System.out.println("線程" + Thread.currentThread().getId() + "執行結束");
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

測試代碼如下

  @Test
    public void test05() throws InterruptedException {
        //51337ms  51148ms
        //52483ms
        long start = System.currentTimeMillis();
        Future<String> task1=ayscService.writeTxt("aaa");
        while (true){
            if(task1.isDone() ) {
                break;
            }
            Thread.sleep(1000);
        }
        long end = System.currentTimeMillis();

        System.out.println("任務全部完成,總耗時:" + (end - start) + "毫秒");
}

  

但是發現從始至終都只有一個線程在跑,后來參考了其他博客才發現自己存在的問題:沒有將方法拆開並且調用方也應該是其他類來調用,博客地址:

http://blog.didispace.com/springbootasync/

最后做下總結:

1.多線程用在多個可以並行執行的任務

2.使用多線程時,注意調用方要是另外的類(使用公共線程池)

3.springboot使用多線程時記得開啟注解

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM