V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
cirton
V2EX  ›  Java

为什么多线程中使用 Future 获取不到异常?

  •  
  •   cirton · 2019-03-11 14:52:23 +08:00 · 2494 次点击
    这是一个创建于 1885 天前的主题,其中的信息可能已经有所发展或是发生改变。

    java 多线程, 程序执行时,想使用 Future 特性捕获异常,做进一步的处理。运行程序时发生了异常,但并没有捕获到异常。

    相关代码结构如下:

    ExecutorService executor = Executors.newFixedThreadPool(3);
    Future<Object> future = null;
    
    for (int i = 0; i < 3; i++) {
    			future = executor.submit(new ThreadDemo());
    			
    			try {
    				 future.get();
    			} catch (InterruptedException e) {
    				System.out.println(String.format("handle exception in child thread. %s", e));
     			} catch (ExecutionException e) {
    				System.out.println(String.format("handle exception in child thread. %s", e));
     			}
    		}
            
    ///// call 方法实现
    @Override
    		public String call() throws Exception {
            
    			try {
    				client.runMethod(ip);
    			} catch (Exception e) {
    				System.out.println(String.format("handle exception in child thread. %s", e)); 			
    			}
    			
    			return "";
    		}
    
    

    在服务器端执行程序时报错,但并未捕获到异常。

    java.rmi.ConnectException: Connection refused to host: 172.17.0.6; nested exception is: 
            java.net.ConnectException: Connection refused (Connection refused)
            at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619)
            at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
            at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
            at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:338)
            at sun.rmi.registry.RegistryImpl_Stub.lookup(RegistryImpl_Stub.java:112)
            at java.rmi.Naming.lookup(Naming.java:101)
            at com.net.client.DataNodeRemoteClient.runRemoteMethod(DataNodeRemoteClient.java:27)
            at com.net.client.DataNodeRemoteClientCallableThread$runTheThread.call(DataNodeRemoteClientCallableThread.java:84)
            at com.net.client.DataNodeRemoteClientCallableThread$runTheThread.call(DataNodeRemoteClientCallableThread.java:1)
            at java.util.concurrent.FutureTask.run(FutureTask.java:266)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
            at java.lang.Thread.run(Thread.java:748)
    Caused by: java.net.ConnectException: Connection refused (Connection refused)
    

    是少了哪些步骤或者哪里操作有问题?

    第 1 条附言  ·  2019-03-12 14:59:50 +08:00
    原因已找到,在 call 方法中调用的方法已经做了异常处理。
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1087 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 19:59 · PVG 03:59 · LAX 12:59 · JFK 15:59
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.