有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多线程Java线程:竞争条件与同步

即使调用代码块是同步的,竞争条件也会发生。再想想,这似乎是一个锁的问题。请查看下面的简单代码块(代码将更好地解释它)-

class CriticalSectionTest {

    public void initWithSync() {
        final CriticalSection cSection = new CriticalSection();

        Thread threadA = new Thread(new Runnable() {
            @Override public void run() {
                synchronized (cSection) {
                    cSection.add(2);
                    System.out.println(
                            "Value after adding from thread-A: " + cSection.getCount());
                }
            }
        });

        Thread threadB = new Thread(new Runnable() {
            @Override public void run() {
                synchronized (cSection) {
                    cSection.add(3);
                    System.out.println(
                            "Value after adding from thread-B: " + cSection.getCount());
                }
            }
        });

        threadA.start();
        threadB.start();

        //Desired output:
        //A: 2
        //B: 5
    }
}

class CriticalSection {
    private long count = 0;

    public void add(long value) {
        /* This method was not made synchronized, intentionally as its done in caller class
         */
        this.count = this.count + value;
    }

    public long getCount() {
        return count;
    }
}

在多次运行时,它会打印以下输出-

这不好

Value after adding from thread-B: 3
Value after adding from thread-A: 5

看起来不错

Value after adding from thread-A: 2 
Value after adding from thread-B: 5

有什么解释吗?还是我错过了一些基本的东西


共 (1) 个答案

  1. # 1 楼答案

    每个线程的开始顺序都不安全Main线程将一个接一个地启动线程,但没有任何东西阻止以下操作:

    THREAD A : START
    THREAD B : START
    THREAD A : WAIT
    THREAD B : RUN
    THREAD A : RUN
    THREAD A : STOP
    THREAD B : STOP
    

    threadB有时可能在threadA之前开始治疗,这就是你现在面临的问题