SpringBoot使用线程池 创建线程消耗cpu
往线程池提交死循环任务,消耗cpu
@Controller
public class TestController {
private static final Logger logger = LoggerFactory.getLogger(TestController.class);
private static ExecutorService threadPool;
@GetMapping("/new-thread")
@ResponseBody
public String newThread(@RequestParam("count") Integer count) {
if (count <= 0 || count >= 8) {
return "too many threads";
}
if (threadPool == null) {
threadPool = new ThreadPoolExecutor(8, 16, 1, TimeUnit.MINUTES,
new ArrayBlockingQueue<>(16, true),
Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
}
for (int i = 0; i < count; i++) {
threadPool.execute(() -> {
while (!Thread.interrupted()) {
}
});
}
return "ok";
}
@GetMapping("/shutdown-thread")
@ResponseBody
public String shutdownThreadPool() {
try {
threadPool.shutdown();
threadPool.awaitTermination(5, TimeUnit.SECONDS);
} catch (Exception e) {
e.printStackTrace();
} finally {
threadPool.shutdownNow();
}
if (threadPool.isShutdown()) {
System.out.println("thread pool is shut down");
}
return "shutdown";
}
}
这里提交的thread一定要能被中断,否则线程池关闭后线程仍在执行