使用Spring ThreadPoolTaskExecutor實現多線程任務


我們為何使用多線程,之前已經有講過了,為了更快的處理多個任務,分割任務,或者調用多個毫無關聯的第三方服務

其實spring就提供了ThreadPoolTaskExecutor這個類來實現線程池,線程池是啥,可以理解為數據源,或者有一堆線程的池子也行

在spring配置中我們可以寫好如下代碼(大致意思都在注釋中,不多說了,百度也一堆):

<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
         <!-- 核心線程數 -->
        <property name="corePoolSize" value="5" />
        <!-- 最大線程數 -->
        <property name="maxPoolSize" value="10" />
        <!-- 隊列最大長度 >=mainExecutor.maxSize -->
        <property name="queueCapacity" value="25" />
        <!-- 線程池維護線程所允許的空閑時間 -->
        <property name="keepAliveSeconds" value="3000" />
        <!-- 線程池對拒絕任務(無線程可用)的處理策略 ThreadPoolExecutor.CallerRunsPolicy策略 ,調用者的線程會執行該任務,如果執行器已關閉,則丟棄.  -->
        <property name="rejectedExecutionHandler">
            <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
        </property>
    </bean>

 

然后定義一個component組件,然后線程的引用就十分簡單了,只要把這個線程扔進這個線程池子就行了

@Component
public class FileCutter {
    
    @Autowired
    private TaskExecutor taskExecutor;
    
    public void filesMng(String path, String fileName) {
        this.taskExecutor.execute(new CutFilesThread(path,fileName));
    }
    
    private class CutFilesThread implements Runnable {
        private String path;
        private String fileName;
        private CutFilesThread(String path, String fileName) {
            super();
            this.path = path;
            this.fileName = fileName;
        }
        @Override
        public void run() {
            System.out.println("barry... run...");
//            display(path, fileName);
        }
    }

 

最后在你所需要的地方就可以調用這個組件了,不論是service還是controller都行

@Autowired
    private FileCutter fileCutter;
    
    @RequestMapping("/cut")
    @ResponseBody
    public Object cut(){
        fileCutter.filesMng("your path", "your fileName");
        return "success";
    }

 

如果不用線程處理,那么使用消息隊列來處理大數據量操作,文件操作,或者並發,都可以。


免責聲明!

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



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