Why do threads through a loop give an error when with Executor

Viewed 284

The sample code is taken from the Java Philosophy 2015 book and it used Java SE5/6. I used JDK11, maybe this code is not suitable for the new version, but why?

public static void main(String[] args) { 
    ExecutorService exec = Executors.newCachedThreadPool(); 
    for(int i=0;i<5;i++) { 
        exec.execute(new LiftOff2());
        exec.shutdown();
    }
} 
Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task LiftOff2@5f205aa rejected from java.util.concurrent.ThreadPoolExecutor@6d86b085[Shutting down, pool size = 1, active threads = 1, queued tasks = 0, completed tasks = 0]
    at java.base/java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2055)
    at java.base/java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:825)
    at java.base/java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1355)
    at Runnable_p897.main(Runnable_p897.java:8)
1 Answers
Related