如何查看未来对象执行的线程(名称)?

问题描述 投票:0回答:1

下面的代码是我做了一个提交给执行者服务的实例,它的结果是我存储在未来对象中的。有什么办法可以让我从未来对象中看到给出结果的线程名称。例如,如果线程1返回了一个4的Integer值,并且这个值被存储在一个未来对象中。我如何知道线程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;
  }
}
java future executorservice java-threads callable
1个回答
2
投票

而不是一个 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;
}
© www.soinside.com 2019 - 2024. All rights reserved.