This question already has answers here:
Thread.join() equivalent in executor
                                
                                    (5个答案)
                                
                        
                                2年前关闭。
            
                    
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

public class Synchronized{
    public static AtomicInteger count = new AtomicInteger(0);
    public static synchronized void increment() {
        count.incrementAndGet();
    }
    public static void main(String[] args) {
        ExecutorService exector = Executors.newFixedThreadPool(2);
        IntStream.range(0, 1000).forEach( i -> exector.submit(Synchronized:: increment));
        System.out.println(count.get());
    }
}


最后不打印1000。它可以打印600至1000的任意位置。因此看来它不是线程安全的。有人可以解释为什么这不是线程安全的吗?

最佳答案

您无需等待任务的执行。您的流将任务移交给池,然后立即打印出计数器的当前(即非最终)值。计数器会适当增加,但您过早要求其值。您将不得不等待执行程序完成,然后再执行sysout。

阅读this answer有关shutdown()awaitTermination()的用法。

10-04 20:44