private final ThreadPoolExecutor executorService = new ThreadPoolExecutor(0, 20, 60, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1000), new ThreadPoolExecutor.CallerRunsPolicy()); @GetMapping("/hello") public void hello(){ executorService.execute(()->{ System.out.println("sleep1"); try { Thread.sleep(5000); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("sleep2"); }); System.out.println("hello"); try { Thread.sleep(2000); } catch (InterruptedException e) { throw new RuntimeException(e); } executorService.execute(()->{ System.out.println("sleep3"); System.out.println("sleep4"); }); }
效果:
hello
sleep1
sleep2
sleep3
sleep4
单线程执行