我想在有时间限制的后台执行一些工作。问题是,我不想阻塞主线程。
天真的实现是有两个执行器服务。一个用于调度/超时,第二个负责完成工作。
final ExecutorService backgroundExecutor = Executors.newSingleThreadExecutor();
final ExecutorService workerExecutor = Executors.newCachedThreadExecutor();
backgroundExecutor.execute(new Runnable() {
public void run() {
Future future = workerExecutor.submit(new Runnable() {
public void run() {
// do work
}
});
try {
future.get(120 * 1000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
logger.error("InterruptedException while notifyTransactionStateChangeListeners()", e);
future.cancel(true);
} catch (ExecutionException e) {
logger.error("ExecutionException", e);
} catch (TimeoutException e) {
logger.error("TimeoutException", e);
future.cancel(true);
}
}
});
还有其他解决方案吗?