1. 程式人生 > >在Springboot中使用執行緒池ThreadPoolTaskExecutor

在Springboot中使用執行緒池ThreadPoolTaskExecutor

package com.markor.template.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * @describe:
 * @author: caichangmeng <[email protected]>
 * @since: 2018/10/22
 */
@Configuration
public class ThreadConfig {
    @Bean
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(3);
        taskExecutor.setMaxPoolSize(7);
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        return taskExecutor;
    }
}
package com.markor.template.controller.thread;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @describe:
 * @author: caichangmeng <
[email protected]
> * @since: 2018/10/22 */ @RestController @RequestMapping("thread") public class ThreadController { @Autowired private ThreadPoolTaskExecutor taskExecutor; /** * @Date: 2018/10/22 * @describe: 無返回值 * @param null : * @return : null * @throws: */ @GetMapping("test") public String threadTest() { taskExecutor.execute(new Runnable() { public void run() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("***************************"); System.out.println(Thread.currentThread().getName()); System.out.println("***************************"); } }); System.out.println("***********threadTest***********"); return "success"; } /** * @Date: 2018/10/22 * @describe: 有參返回方法 * @param null : * @return : null * @throws: */ @GetMapping("hasReturn") public String hasReturn() throws ExecutionException, InterruptedException { Future<String> future = taskExecutor.submit(new Callable<String>() { public String call() throws Exception { Thread.sleep(3000); System.out.println("***************************"); System.out.println(Thread.currentThread().getName()); System.out.println("***************************"); return "執行成功"; } }); System.out.println("***********hasReturn***********"); String returnStr = future.get(); System.out.println("***********end***********"); return "success"; } }