简体   繁体   English

为什么在使用 Executor 时通过循环的线程会出错

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

The sample code is taken from the Java Philosophy 2015 book and it used Java SE5/6.示例代码取自 Java Philosophy 2015 一书,它使用了 Java SE5/6。 I used JDK11, maybe this code is not suitable for the new version, but why?我用的是JDK11,可能这段代码不适合新版本,但为什么呢?

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)

From the documentation of ExecutorService::shutdown :ExecutorService::shutdown的文档

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted .启动有序关闭,其中执行先前提交的任务,但不会接受新任务 ... ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么Executor框架中的任务是线程 - Why Tasks in Executor Framework are Threads 为什么 executor 在其线程以异常结束时没有用完可用线程? - Why executor is not running out of available threads when its threads ends up with exceptions? 如何为Executor选择线程数 - how do I choose number of threads for Executor 为什么 executor.isShutdown() 在其池中仍有线程运行时返回 true? - Why executor.isShutdown() returns true when there are threads still running in it's pool? Threadpool Executor完成后如何给出消息? - How to give message when Threadpool Executor is completed? 为什么在没有睡眠的主线程中使用 while(true) 循环时子线程不起作用? - Why Child Threads do not work when using while(true) loop in main thread without sleep? 当使用“ for”循环将数据存入数组时,为什么Java会给出运行时错误? - Why does Java give runtime error when depositing data into an array using a “for” loop? 为什么这个程序运行时会报错 - Why does this program give an error when run 为什么在尝试将词法分析器作为 ANTLRv4 中 CommonTokenStream 的输入时出现错误 - Why do I get an error when trying to give a lexer as input of CommonTokenStream in ANTLRv4 使用while循环和Executor时JFrame不出现 - JFrame not appearing when using while loop and Executor
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM