为什么当线程池中的一个线程抛出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();
}
}
}
}
答案 0 :(得分:4)
线程池中没有线程抛出RejectedExecutionException
。将任务提交给线程池的主要线程实际上是抛出RejectedExecutionException
。
主要线程不会在提交时阻止,因为规范规定它不应该。有机制可以做到这一点,请参阅 ThreadPoolExecutor Block When Queue Is Full?