java 判断方法调用是否超时 设置方法调用的超时时间

java 判断方法调用是否超时 设置方法调用的超时时间

public class Test {
    public static void main(String[] args) {
        Executor executor=Executors.newSingleThreadExecutor();
        FutureTask<String> future=new FutureTask<String>(new Callable<String>() {
            public String call() throws Exception {
                // TODO Auto-generated method stub
                Test m=new Test();
                return m.getValue();
            }
        });
        executor.execute(future);
        try{
            String result=future.get(1, TimeUnit.SECONDS);
            System.out.println(result);
        }catch (InterruptedException e) {
            // TODO: handle exception
           System.out.println("方法执行中断");
          // future.cancel(true);
        }catch (ExecutionException e) {
             System.out.println("Excution异常");
            // TODO: handle exception
            future.cancel(true);
        }catch (TimeoutException e) {
            // TODO: handle exception
             System.out.println("方法执行时间超时");
            //future.cancel(true);
        }
        System.out.println("爱上大声地");
    }
    public String getValue(){
        try{
            Thread.sleep(1000);
        }catch (Exception e) {

            e.printStackTrace();// TODO: handle exception
        }
        return "阿斯顿撒旦阿斯顿 sad";
    }
}
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值