为线程执行设置timeout

package com.test.threads;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
* @author Hawkins
*
*
*在指定时间内执行某个task,超时则退出执行。
*/
public class TimedCall {
public static void main(String[] args) throws InterruptedException,
ExecutionException, TimeoutException {
long timeout = 1000;// 任务必须在设定时间内完成,否则任务将被强制关闭
long timeNeed = 2000;// 任务完成需要的时长。
TimeUnit timeUnit = TimeUnit.MILLISECONDS;// 时间单位
ExecutorService executor = Executors.newSingleThreadExecutor();// 高级并发API

Runnable task = new MyThread(timeNeed, timeUnit);

while (!timedCall(executor, task, timeout, timeUnit))
;// 在某些场景下,需要不断尝试执行任务,直到能够在限定时间内执行完毕。

}

private static boolean timedCall(ExecutorService executor, Runnable c,
long timeout, TimeUnit timeUnit) throws InterruptedException,
ExecutionException {
// FutureTask<?> task = new FutureTask<Object>(c, null);
// executor.execute(task);
//
// task.get(timeout, timeUnit);
Future<?> future = executor.submit(c);
try {
future.get(timeout, timeUnit);
return true;
} catch (TimeoutException e) {
future.cancel(true);// 参数设为true,向执行线程发送中断通知。否则,允许已经启动的线程继续执行直到完成任务。
System.err.println("任务执行超时,强制退出");
return false;
}
}
}

class MyThread implements Runnable {
long timeLong = 0;// how long thread running will cost
TimeUnit timeUnit;

public MyThread() {
}

public MyThread(long milli, TimeUnit timeUnit) {
this.timeLong = milli;
this.timeUnit = timeUnit;
}

@Override
public void run() {
System.out.println("---------" + Thread.currentThread().getName()
+ "开始执行,时长[" + timeLong + "]------");
try {
Thread.sleep(timeLong);
} catch (InterruptedException e) {
System.err.println("线程中断,退出");
return;// 必须响应中断,否则无法退出线程。在退出之前你可能还需做一些资源回收等等。
}
System.out.println("---------" + Thread.currentThread().getName()
+ "执行完毕,时长[" + timeLong + "]------");

}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值