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

2019-03-11 14:52:23 +08:00
 cirton

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)

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

2516 次点击
所在节点    Java
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/543324

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX