1、同一个线程池可以执行不同的任务类型,也可以带返回值,也可以不带返回值的
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.vip.vman.result.BasicResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.*;
@Slf4j
@RestController
@RequestMapping(value = "/vman/thread")
public class Thread2Controller {
ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("thread-get-all-test-%d").build();
private final ExecutorService executorService = new ThreadPoolExecutor(3,60, 180L, TimeUnit.SECONDS,new LinkedBlockingQueue(),namedThreadFactory);
/**
* 带返回值的任务执行
*/
@RequestMapping(value = "/test1", method = RequestMethod.GET)
public BasicResult executeTask4(String id) throws InterruptedException, ExecutionException {
BasicResult basicResult = new BasicResult();
Future future= executorService.submit(() -> {
return id + "rest1";
});
basicResult.setCodeMessage("0", future.get());
return basicResult;
}
/**
* 不带返回值的任务执行
*/
@RequestMapping(value = "/test2", method = RequestMethod.GET)
public BasicResult executeTask43(String id) throws InterruptedException, ExecutionException {
BasicResult basicResult = new BasicResult();
executorService.execute(() -> {
log.info("test2,id:{}", id);
});
basicResult.setCodeMessage("0", id);
return basicResult;
}
}
多任务共用一个大的线程池还是每个任务单独使用线程池? - 掘金