java測试网络连接是否成功并设置超时时间

/**
     * 获取RMI接口状态
     *
     * @return "0":服务正常,"1":  连接报错,"2":连接超时
     */
    @Override
    public String getRMIJkzt() {
        final ExecutorService es = Executors.newFixedThreadPool(1);
        Callable<String> callable = new Callable<String>() {//使用Callable接口作为构造參数
            @Override
            public String call() throws Exception {//真正的任务在这里运行。这里的返回值类型为String,能够为随意类型
                URL url = new URL("rmi://192.168.20.188:1098/ht");
                InputStream in = url.openStream();
                in.close();
                return "0";
            }
        };
        try {
            Future future = es.submit(callable);
            String value = null;
            try {
                value = future.get(5000, TimeUnit.MILLISECONDS).toString();//取得结果,同一时候设置超时运行时间为5秒。相同能够用future.get(),不设置运行超时时间取得结果
                return "0";
            } catch (ExecutionException e) {
                return "1";
            } catch (TimeoutException e) {
                return "2";
            }
        } catch (InterruptedException e) {
            return "1";
        }
    }

posted on 2017-06-15 09:43  yjbjingcha  阅读(1213)  评论(0编辑  收藏  举报

导航