Java 在web应用程序中使用ThreadPoolExecutor
我计划在我的一个web应用程序中使用ThreadPoolExecutor,但我有如下查询 如果我的ThreadPoolExecutor在应用程序未收到请求时关闭/终止该怎么办。我是否必须检查状态并启动新的ThreadPoolExecutor对象。实际何时会发生自动终止/关闭 当我在测试场景下运行时,它并没有关闭/终止。 我的设想是: 我的web应用程序不断获取读取参数的请求,发送ACK,并使用参数进行进一步处理Java 在web应用程序中使用ThreadPoolExecutor,java,multithreading,concurrency,Java,Multithreading,Concurrency,我计划在我的一个web应用程序中使用ThreadPoolExecutor,但我有如下查询 如果我的ThreadPoolExecutor在应用程序未收到请求时关闭/终止该怎么办。我是否必须检查状态并启动新的ThreadPoolExecutor对象。实际何时会发生自动终止/关闭 当我在测试场景下运行时,它并没有关闭/终止。 我的设想是: 我的web应用程序不断获取读取参数的请求,发送ACK,并使用参数进行进一步处理 public static void main(String[] args) {
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());
}
publicstaticvoidmain(字符串[]args){
ThreadPoolTester tt=新的ThreadPoolTester();
BlockingQueue workQueue=新的SynchronousQueue();
ThreadPoolExecutor ex=新的ThreadPoolExecutor(10,Integer.MAX_值,10,TimeUnit.millides,workQueue);
while(true){
tt.执行人(ex);
试一试{
睡眠(10000);
}捕捉(中断异常e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
}
公共作废执行器(线程池执行器ex){
ArrayList tasks=新建ArrayList();
如果(例如isShutdown()){
System.out.println(“线程池已关闭”);
}
如果(不包括()项){
System.out.println(“线程池终止”);
}
对于(int i=0;i,ThreadPoolExecutor本身永远不会关闭。但是,如果线程空闲时间超过您指定的保持活动时间,它将关闭线程。但它将根据需要自动创建新线程
所以你什么都不用做
如果您甚至希望线程永远保持活动状态,可以使用固定大小的线程池,但这当然是不可伸缩的