正常关闭线程和执行器
下面的代码段试图解决这个问题。
代码将永久循环,并检查是否有任何挂起的请求需要处理。如果有的话,它会创建一个新线程来处理请求并将其提交给执行程序。完成所有线程后,它会休眠 60 秒,并再次检查挂起的请求。
public static void main(String a[]){
//variables init code omitted
ExecutorService service = Executors.newFixedThreadPool(15);
ExecutorCompletionService<Long> comp = new ExecutorCompletionService<Long>(service);
while(true){
List<AppRequest> pending = service.findPendingRequests();
int noPending = pending.size();
if (noPending > 0) {
for (AppRequest req : pending) {
Callable<Long> worker = new RequestThread(something, req);
comp.submit(worker);
}
}
for (int i = 0; i < noPending; i++) {
try {
Future<Long> f = comp.take();
long name;
try {
name = f.get();
LOGGER.debug(name + " got completed");
} catch (ExecutionException e) {
LOGGER.error(e.toString());
}
} catch (InterruptedException e) {
LOGGER.error(e.toString());
}
}
TimeUnit.SECONDS.sleep(60);
}
}
我的问题是这些线程完成的大部分处理都与数据库有关。该程序将在Windows机器上运行。当有人尝试关闭或注销计算机时,这些线程会发生什么情况?如何优雅地关闭正在运行的线程以及执行器?