如何查看从将来的对象执行了哪个线程(名称)



下面的代码是我制作提交到执行器服务的实例,其结果是我存储在未来对象中的内容。有什么方法可以查看从未来对象给出结果的线程的名称。例如,如果线程 1 返回 Integer 值 4,并且该值存储在将来的对象中。我怎么知道线程 1 是执行并返回值 4 的线程?如果我没有正确解释,请随时澄清。

class Test implements Callable<Integer>{
Integer i;
String threadName;
public Test(Integer i){
this.i = i;
}
public Integer call() throws Exception{
threadName = Thread.currentThread().getName();
System.out.println(Thread.currentThread().getName());
Thread.sleep(i * 1000);
return i ;
}
public String toString(){
return threadName;
}
}

您可以返回一个包含结果和线程名称的对象,而不是Integer

public static class ResultHolder {
public Integer result;
public String threadName;
}
[...]
public ResultHolder call() throws Exception {
ResultHolder ret = new ResultHolder();
ret.threadName = Thread.currentThread().getName();
ret.result = i;
Thread.sleep(i.intValue() * 1000);
return ret;
}

最新更新