直接上代码:
private static ExecutorService executorService = Executors.newSingleThreadExecutor();
/**
* @param args
*/
public static void main(String[] args) {
long start = System.currentTimeMillis();
String result = timeoutMethod(5000);
System.out.println("方法实际耗时:" + (System.currentTimeMillis() - start) + "毫秒");
System.out.println("结果:" + result);
try {
Thread.sleep(8000);
long start1 = System.currentTimeMillis();
String result1 = timeoutMethod(5000);
System.out.println("方法实际耗时:" + (System.currentTimeMillis() - start1) + "毫秒");
System.out.println("结果:" + result1);
} catch (Exception e) {
}
}
private static String timeoutMethod(int timeout) {
String result = "超时标志";
FutureTask futureTask = new FutureTask<>(() -> unknowMethod());
executorService.execute(futureTask);
try {
result = futureTask.get(timeout, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
futureTask.cancel(true);
result = "超时标志";
}
return result;
}
private static String unknowMethod() {
Random random = new Random();
int time = (random.nextInt(10) + 1) * 1000;
System.out.println("任务将耗时: " + time + "毫秒");
try {
Thread.sleep(time);
} catch (Exception e) {
}
return "真实结果";
}
运行结果1:
任务将耗时: 2000毫秒
方法实际耗时:2044毫秒
结果:真实结果
任务将耗时: 4000毫秒
方法实际耗时:4000毫秒
结果:真实结果
运行结果2:
任务将耗时: 7000毫秒
方法实际耗时:5037毫秒
结果:超时标志
任务将耗时: 9000毫秒
方法实际耗时:5001毫秒
结果:超时标志