Java中的超时机制 - 执行一段有时间限制的任务

1. 场景描述
举个例子,有时候执行一段程序需要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)
		{
			result = Boolean.FALSE;
			e.printStackTrace();
		}
		finally
		{
			threadPool.shutdownNow();
		}
		
		return result;
	}
}

3. 测试
package org.demo.task;

import java.util.concurrent.Callable;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		boolean result = TimeoutTaskUtils.execute(new MyTimeoutTask(), 5);
		System.out.println("result = " + result);
		System.out.println("-- finished. --");
	}

}
class MyTimeoutTask implements Callable<Boolean> {
	
	@Override
	public Boolean call() throws Exception {
		for (int i=0; i<10; i++) {
		    System.out.println("i = " + i);
			Thread.sleep(1000);
		}
		return true;
	}
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值