您的位置:首页 > 其它

获取线程执行结果

2016-10-24 14:42 369 查看
如果线程执行过程中抛出异常,在获取结果时会hang在出错线程上,而其他线程的结果不会被获取。

package com.test;

import java.util.ArrayList;

import java.util.List;

import java.util.concurrent.Callable;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Future;

public class ExecutorExceptionTest {

static class Result {

private String name;
private String value;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getValue() {
return value;
}

public void setValue(String value) {
this.value = value;
}

public Result(String name, String value) {
this.name = name;
this.value = value;
}

@Override
public String toString() {
return "Result [name=" + name + ", value=" + value + "]";
}

}

static class Task implements Callable<Result> {

private String name;

private int value;

public Task(String name, int value) {
this.name = name;
this.value = value;
}

@Override
public Result call() throws Exception {
System.out.println(name + " begin*********************");
if (value % 2 == 1)
throw new Exception(name + "the task failed!");
System.out.println(name + " end-------------------------");
return new Result(name, "number value is " + value);
}

}

public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executor = Executors.newFixedThreadPool(5);
List<Task> tasks = new ArrayList<Task>();
for (int i = 0; i < 5; i++) {
Task task = new Task("task" + i, i);
tasks.add(task);
}
List<Future<Result>> results = executor.invokeAll(tasks);

for (int i = 0; i < results.size(); i++) {
Future<Result> result = results.get(i);
Result resultValue = result.get();
System.out.println(resultValue);
}
}


}

consle log

task0 begin*********************

task1 begin*********************

task0 end————————-

task2 begin*********************

task2 end————————-

task3 begin*********************

task4 begin*********************

task4 end————————-

Result [name=task0, value=number value is 0]

Exception in thread “main” java.util.concurrent.ExecutionException: java.lang.Exception: task1the task failed!

at java.util.concurrent.FutureTask.report(FutureTask.java:122)

at java.util.concurrent.FutureTask.get(FutureTask.java:188)

at com.test.ExecutorExceptionTest.main(ExecutorExceptionTest.java:80)

Caused by: java.lang.Exception: task1the task failed!

at com.test.ExecutorExceptionTestTask.call(ExecutorExceptionTest.java:62)atcom.test.ExecutorExceptionTestTask.call(ExecutorExceptionTest.java:1)

at java.util.concurrent.FutureTask.run(FutureTask.java:262)

at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)

at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)

at java.lang.Thread.run(Thread.java:745)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  线程 异常