저는 ThreadPool과 ExecutorService를 사용하여 1에서 9까지의 숫자를 세는 간단한 프로그램을 가지고 있습니다. 각 스레드는 1 초 동안 실행을 기다리고 있습니다. 그러나 아래의 프로그램은 각 실행마다 임의의 결과를 제공합니다. 나는이 문제를 해결하는 방법을 잘 모르겠습니다 항상 45ExecutorService를 사용하는 동시성
어떤 도움을주십시오을 생산!
public static void main(String[] args) throws InterruptedException {
AtomicLong count = new AtomicLong(0);
ExecutorService executor = Executors.newFixedThreadPool(10);
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
for(Integer i : list) {
executor.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
count.set(count.get() + i);
}
});
}
System.out.println("Waiting...");
executor.shutdown();
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);
System.out.println("Total::"+count.get());
System.out.println("Done");
}
가능한 복제 [경쟁 조건이 무엇입니까?] (https://stackoverflow.com/questions/34510/what-is-a-race-condition) –