gpt4 book ai didi

java - RejectedExecutionException 后调用线程不会停止

转载 作者:行者123 更新时间:2023-11-29 08:34:35 26 4
gpt4 key购买 nike

为什么当来自线程池的线程之一抛出 RejectedExecutionException 时主线程没有停止?我在这里做错了吗?线程池中的第三个线程抛出 RejectedExecutionException 并且我没有在主线程中处理这个异常。所以我是否必须处理此异常以使我的主线程停止。任何帮助,将不胜感激。

    public static void main(String[] args) {
ExecutorService threadPool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<Runnable>(1));
threadPool.execute(new TestOne());
threadPool.execute(new TestTwo());
threadPool.execute(new TestThree());
threadPool.shutdown();
try {
threadPool.awaitTermination(2L, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("main thread stopped");
}
}

class TestOne implements Runnable {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Executing task one");
try {
Thread.sleep(10);
} catch (Throwable e) {
e.printStackTrace();
}
}

}
}

class TestTwo implements Runnable {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Executing task two");
try {
Thread.sleep(10);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
}

class TestThree implements Runnable {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Executing task three");
try {
Thread.sleep(10);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
}

最佳答案

线程池中没有线程抛出 RejectedExecutionException。将任务提交到线程池的主线程实际上抛出了 RejectedExecutionException

主线程不会在提交时阻塞,因为规范规定它不应该阻塞。有一些机制可以做到这一点,请参阅 ThreadPoolExecutor Block When Queue Is Full?

关于java - RejectedExecutionException 后调用线程不会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45173693/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com