zoukankan      html  css  js  c++  java
  • FutureTask取结果超时代码小测试

    public static void main(String[] args) throws TimeoutException{
                Callable<Integer> callable1 = new Callable<Integer>() {
                    public Integer call() throws Exception {
                        Thread.sleep(5000); -- 故意执行五秒
                        return new Random().nextInt(100);
                    }
                };
                Callable<Integer> callable2 = new Callable<Integer>() {
                    public Integer call() throws Exception {
                        return new Random().nextInt(100);
                    }
                };
                FutureTask<Integer> future1 = new FutureTask<Integer>(callable1);
                FutureTask<Integer> future2 = new FutureTask<Integer>(callable2);
                
    //            new Thread(future1).start();
                ExecutorService service = Executors.newFixedThreadPool(3);
                service.submit(future1);
                service.submit(future2);
                try {
    //                Thread.sleep(1000);// 可能做一些事情
                    try
                    {
                        System.out.println(future1.get(4000,TimeUnit.MILLISECONDS)); -- 4秒超时
                        
                    }
                    catch (TimeoutException e)
                    {
                        System.out.println("time out");
                    }
                    System.out.println(future2.get(4000,TimeUnit.MILLISECONDS));
                    
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }

    执行结果

    time out
    25

    结论:

    1  future1.get 会阻塞 future2.get由于在后面所以不会执行

    2  future1.get发生了超时,此时至少已经等待了4秒了。但是future2.get是可以正常返回的,说明超时时间是call方法中执行的时间。

    另外的小发现,try 块中如果第一句发生了异常,那么try 块中剩余语句均不执行。java都搞了3年多了,才意识到这个知识点,真是惭愧。

     
  • 相关阅读:
    MySQL 中now()时间戳用法
    ajax local.href不跳转的原因之一
    Call to a member function select() on string错误
    TP框架中ajax post请求时提示404
    TP框架中field查询字段
    jQuery如何获得select选中的值?input单选radio选中的值
    TP框架中session操作
    InnerHtml() 与html( )的区别
    C++开源项目等收集
    RCU-数据库初始化参数
  • 原文地址:https://www.cnblogs.com/juniorMa/p/5851789.html
Copyright © 2011-2022 走看看