在ExecutorService和期貨列表的幫助下,我已經在Java中創建了一個線程池。 我創建了一個實現Callable接口的RandomProcess類,並覆蓋了調用方法 以執行某些操作。通過ExecutorService在線程中所做的更改在執行後不會反映
它看起來像這樣:
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;
}
我在這個班,是應該能反映出在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;
}
}
無法弄清楚問題可能是什麼。
它爲什麼要反映任何東西?你只是在重寫'result'的內部引用,而不是添加/修飾任何東西。 –
您好@ M.Deinum您能否告訴我們如何檢查結果中所做的更改,以便在檢查方法中使用它們。 Thnx –
**如何返回**結果,而不是總是返回1?然後f.get()也會返回這個結果。 –