【发布时间】:2010-07-26 07:02:27
【问题描述】:
以下代码尝试完成此操作。
代码永远循环并检查是否有任何待处理的请求需要处理。如果有,它会创建一个新线程来处理请求并将其提交给执行程序。所有线程完成后,它会休眠 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 机器上运行。当有人试图关闭或注销机器时,这些线程会发生什么?如何优雅地关闭正在运行的线程和执行器。?
【问题讨论】:
标签: java multithreading