我刚刚读取this article,并认为如果Runnable
的抛出异常并退出,threadpool可能会耗尽工作线程。我做了一个小代码并检查,但池大小没有变化。线程抛出RuntimeException - 对线程池的影响
public class ThreadPoolTest {
public static void main(String[] args) throws InterruptedException {
ThreadPoolExecutor tp = new ThreadPoolExecutor(1, 1, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1));
Thread.sleep(1000);
System.out.println(tp.getPoolSize());
tp.execute(new Runnable(){
@Override
public void run() {
System.out.println("Executing & Throwing");
throw new NullPointerException();
}
});
Thread.sleep(1000);
System.out.println(tp.getPoolSize());
tp.execute(new Runnable(){
@Override
public void run() {
System.out.println("Executing & Throwing");
throw new NullPointerException();
}
});
Thread.sleep(1000);
System.out.println(tp.getPoolSize());
tp.shutdown();
}
}
输出我得到
0
Exception in thread "pool-1-thread-1" java.lang.NullPointerException
at threads.ThreadPoolTest$1.run(ThreadPoolTest.java:18)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Executing & Throwing
1
Exception in thread "pool-1-thread-2" java.lang.NullPointerException
at threads.ThreadPoolTest$2.run(ThreadPoolTest.java:29)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Executing & Throwing
1
这是一个关于Java 7中是否有线程池的实现任何Java在文章中指出这是脆弱?
据我所知,ThreadPoolExecutor的产生一个新的工人来维持游泳池大小。 – 2013-03-15 10:04:41