我在ExecutorService和List of Futures的帮助下用Java创建了一个线程池。 我创建了一个RandomProcess类,它实现了Callable接口并覆盖了call方法 执行某些操作。
看起来像这样:
public class RandomProcess implements Callable<Integer> {
private Result result;
public RandomProcess(Result result) {
super();
this.result = result;
}
@Override
public Integer call() throws Exception {
//performSomeOps returns a Result that has certain values that I need
result = performSomeOps();
return 1;
}
我在这个类中有这个Result对象,它应该反映所做的更改 在Randomprocess线程中。遗憾的是,当我返回此结果时,不会反映这些更改。
public class Abc{
public Result check(){
Result result = new Result(true);
try {
ExecutorService exec = Executors.newFixedThreadPool(7);
List<Future<?>> futures = new ArrayList<Future<?>>(7);
for (Entity entity : randomListOfEntities) {
futures.add(exec.submit(new RandomProcess(result)));
}
for (Future<?> f : futures) {
f.get(); // wait for a process to complete
}
exec.shutdown();
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
无法弄清问题可能是什么。
答案 0 :(得分:1)
In Line result = performSomeOps(); 您没有更新提交线程时传递的结果内部的值。您只是在该行分配新对象而不是更改原始对象。您需要更新结果对象内的值(Something link result.setSomevalue()= performSomeOps()。getSomeValue())或将结果对象传递给performSomeOps(),并在该方法中更新结果。
答案 1 :(得分:0)
需要返回&#34;结果&#34;作为&#34; RandomProcess&#34;的对象线程,然后将反映更改。
公共类RandomProcess实现Callable {
private Result result;
public RandomProcess(Result result) {
super();
this.result = result;
}
@Override
public Result call() throws Exception {
result = performSomeOps();
return result;
}
}