java 线程不运行时间_处理线程最大执行时间的最佳方式(Java)

如何:

提交您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();

主要优点这种方法是,你可以设置每个任务和延迟队列不同的最长执行时间会自动的执行时间量最小剩余返回任务。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值