我计划在我的一个网络应用程序中使用ThreadPoolExecutor,但我有一些疑问,比如当应用程序没有收到请求时,如果我的 ThreadPoolExecutor 关闭/终止怎么办。我是否必须检查状态并启动新的ThreadPoolExecutor对象。实际上何时会发生自动终止/关闭?
当我在测试场景下运行时,它没有关闭/终止。我的场景是这样的:我的网络应用程序不断地获取请求读取参数,发送 ACK 并使用参数进行一些进一步的处理。
public static void main(String[] args) {
ThreadPoolTester tt = new ThreadPoolTester();
BlockingQueue<Runnable> workQueue = new SynchronousQueue<Runnable>();
ThreadPoolExecutor ex = new ThreadPoolExecutor(10, Integer.MAX_VALUE, 10, TimeUnit.MILLISECONDS, workQueue);
while(true){
tt.executor(ex);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void executor(ThreadPoolExecutor ex){
ArrayList<Future<String>> tasks= new ArrayList<Future<String>>();
if(ex.isShutdown()){
System.out.println("threadpool is shutdown");
}
if(ex.isTerminated()){
System.out.println("threadpool is terminated");
}
for(int i=0; i<100; i++){
Future<String> task = ex.submit(new MyTask(i));
tasks.add(task);
System.out.println("Pool Size "+ex.getPoolSize());
}
for (int i = 0; i < 100; i++) {
try{
System.out.println("Retunr value: "+ tasks.get(i).get());
}catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("final size "+ex.getPoolSize());
}