为什么我的同步方法不起作用?

Why isn't my synchronized method working?

简单地说,我想看看使用 sychronized 关键字时的区别,而不是 运行 在没有锁的情况下在线程上设置函数。

在此代码中:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;


public class mainClass {
static int count=0;

public static void main(String[] args) {
    ExecutorService executor = Executors.newFixedThreadPool(2);
    Runnable r =new Runnable() {

        public synchronized void run() {
            count = count + 1;
        }
    };
    IntStream.range(0, 10000)
            .forEach(i -> executor.submit(r::run));

    executor.shutdown();

    System.out.println(count);  // 10000

}
}

它并没有像我预测的那样起作用,它 returns 10000 在大约 40% 的 运行 中。这是为什么?问题出在哪里? 我认为函数 运行 一次只被 1 个线程 运行,所以应该没有问题,但显然我错了。

ExecutorService#shutdown 不等待任务完成。您应该为此使用 awaitTermination

参见documentation for ExecutorService#shutdown

IntStream.range(0, 10000)
        .forEach(i -> executor.submit(r::run));

executor.shutdown();
executor.awaitTermination(1, TimeUnit.MINUTE); // <!-- HERE