首页 > 解决方案 > 在我的情况下,同步关键字不能保证线程安全

问题描述

以下代码让我感到困惑,因为同步关键字不会阻止两个线程同时访问 SafeThread.value。

当我运行代码时,结果不是预期的 20000。

我还尝试使 increment() 非静态并使两个线程具有相同的 SafeThread 实例。它也没有工作。我错过了什么吗?

public class MultithreadTesting extends Thread {
    public static void main(String[] args) {
        MultithreadTesting thread1 = new MultithreadTesting();
        MultithreadTesting thread2 = new MultithreadTesting();
        thread1.start();
        thread2.start();
        System.out.println(SafeThread.value);
    }

    public void run() {
        int i = 10000;
        while (i > 0) {
            SafeThread.increment();
            i--;
        }
    }
}


public class SafeThread {
    public static int value = 0;
    public synchronized static void increment() {
        value++;
    }
}

标签: javamultithreading

解决方案


推荐阅读