1. 场景描述
举个例子,有时候执行一段程序需要1 ~ 10分钟才能运行完,但你最多只能等5分钟。如果5分钟以内程序能够运行完,那么直接返回正确结果;如果过了5分钟程序还没运行完,那么就中止程序的运行,直接返回一个错误结果。
2. 一个工具类(用来执行有时间限制的任务)
举个例子,有时候执行一段程序需要1 ~ 10分钟才能运行完,但你最多只能等5分钟。如果5分钟以内程序能够运行完,那么直接返回正确结果;如果过了5分钟程序还没运行完,那么就中止程序的运行,直接返回一个错误结果。
2. 一个工具类(用来执行有时间限制的任务)
package org.demo.task;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class TimeoutTaskUtils {
/**
* 执行一个有时间限制的任务
* @param task 待执行的任务
* @param seconds 超时时间(单位: 秒)
* @return
*/
public static Boolean execute(Callable<Boolean> task, int seconds)
{
Boolean result = Boolean.FALSE;
ExecutorService threadPool = Executors.newCachedThreadPool();
try
{
Future<Boolean> future = threadPool.submit(task);
result = future.get(seconds, TimeUnit.SECONDS);
}
catch (Exception e)