下面的代码是我创建提交到执行程序服务的实例,其结果是我存储在未来对象中的内容。有什么方法可以看到从 future 对象中给出结果的线程的名称。例如,如果线程 1 返回整数值 4,并且该值存储在 future 对象中。我如何知道线程 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;
}
关于java - 如何从 future 对象中查看执行了哪个线程(名称),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62032027/