如何:
提交您Callable为ExecutorService和保持一个句柄返回Future。
ExecutorService executorService = ... // Create ExecutorService.
Callable callable = new MyCallable(); // Create work to be done.
Future fut = executorService.submit(callable);
裹在Delayed一个实现由此Delayed的getDelay(TimeUnit)方法返回所讨论的工作的最大执行时间Future。
public class DelayedImpl implements Delayed {
private final long maxExecTimeMillis;
private final Future future;
public DelayedImpl(long maxExecTimeMillis, Future future) {
this.maxExecMillis = maxExecMillis;
this.future = future;
}
public TimeUnit getDelay(TimeUnit timeUnit) {
return timeUnit.convert(maxExecTimeMillis, TimeUnit.MILLISECONDS);
}
public Future getFuture() {
return future;
}
}
DelayedImpl impl = new DelayedImpl(3000L, fut); // Max exec. time == 3000ms.
Add the `DelayedImpl` to a `DelayQueue`.
Queue queue = new DelayQueue();
queue.add(impl);
从队列中有一个线程反复take()和检查每个DelayedImpl的Future是否是通过调用isDone()完整的;如果不是,则取消该任务。
new Thread(new Runnable() {
public void run() {
while (!Thread.interrupted) {
DelayedImpl impl = queue.take(); // Perform blocking take.
if (!impl.getFuture().isDone()) {
impl.getFuture().cancel(true);
}
}
}
}).start();
主要优点这种方法是,你可以设置每个任务和延迟队列不同的最长执行时间会自动的执行时间量最小剩余返回任务。