java控制方法执行时间

需求:控制方法时间在代码指定的长度范围内
实现原理:java.util.concurrent.Future

public static boolean checkDBStatus(){
		boolean bdStatus = false;
		final ExecutorService exec = Executors.newFixedThreadPool(1);
		Callable call = new Callable(){
			public String call() throws Exception{
				//真正的任务在这里执行,这里的返回值类型为String,可以为任意类型
				MethodOver.getValue();
				return "true";
			}
		};

		try{
			Future future = exec.submit(call);
			// set db connection timeout to 10 seconds  
			String obj = future.get(1000*10,TimeUnit.MILLISECONDS);
			bdStatus = Boolean.parseBoolean(obj);
			System.out.println("the return value from call is :" + obj);
		}catch(TimeoutException ex){
			System.out.println("====================task time out===============");
			ex.printStackTrace();
			bdStatus = false;
		}catch(Exception e){
			System.out.println("failed to handle.");
			e.printStackTrace();
			bdStatus = false;
		}
		// close thread pool  
		exec.shutdown();
		return bdStatus;
	}

public static String getValue()
	{
		try{
			Thread.sleep(500);
		}catch (Exception e) {
			
			e.printStackTrace();// TODO: handle exception
		}
		return "ssssssssssssssss";
		
	}
public static void main(String[] args) {
	MethodOver.checkDBStatus();
}
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;
import java.util.concurrent.TimeoutException;

项目实战:


if(!StringUtils.isEmpty(sql)){
	final ExecutorService exec = Executors.newFixedThreadPool(1);
	Callable call = new Callable(){
		public String call() throws Exception{
			reflectMethodManager.invokeMethod(JdbcExtendDataExtImp.BEAN+"."+type+JdbcExtendDataExtImp.EXT,sql);
			return "true";
		}
	};
	try{
		Future future = exec.submit(call);
		future.get(1000*60,TimeUnit.MILLISECONDS);
	}catch(TimeoutException ex){
		System.out.println(fileName+"====================task time out===============");
		isError = true;
		errorMes = fileName+" TimeoutException";
	}catch(Exception e){
		System.out.println("failed to handle.");
		isError = true;
		errorMes = e.getMessage();
	}
	// close thread pool  
	exec.shutdown();
};

你可能感兴趣的:(Java)