Java 在两个线程之间共享一个变量

2022-09-02 20:04:26

我有两个线程。一个调用修改变量的类的 update 方法。另一个调用读取变量的类的 update 方法。只有一个线程写入,一个(或多个)线程读取该变量。由于我是多线程的新手,因此在并发方面我需要做什么?

public class A
{
    public int variable; // Does this need to be volatile?
       // Not only int, could also be boolean or float.
    public void update()
    {
        // Called by one thread constantly
        ++variable;
        // Or some other algorithm
        variable = complexAlgorithm();
    }
}

public class B
{
    public A a;
    public void update()
    {
        // Called by another thread constantly
        // I don't care about missing an update
        int v = a.variable;
        // Do algorithm with v...
    }
}

谢谢


答案 1

如果有一个并且只有一个线程写入,则可以逃脱 制作它 。否则,请参阅答案。

只有在只有一个写入线程的情况下才有效,因为只有一个写入线程,因此它始终具有正确的值 。variablevolatileAtomicIntegervolatilevariable


答案 2

在这种情况下,我会使用AtomicInteger,但是一般化的答案是,对变量的访问应该由同步块保护,或者通过使用java.util.concurrent包的另一部分来保护。

举几个例子:

使用同步

public class A {
    public final Object variable;
    public void update() {
        synchronized(variable) {
            variable.complexAlgorithm();
        }
    }
}

public class B {
    public A a;
    public void update() {
        sychronized(a.variable) {
            consume(a.variable);
        }
    }
}

使用 java.util.concurrent

public class A {
    public final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    public final Object variable;
    public void update() {
        lock.writeLock().lock();
        try {
            variable.complexAlgorithm();
        } finally {
            lock.writeLock().unlock();
        }
    }
}

public class B {
    public A a;
    public void update() {
        a.lock.readLock().lock();
        try {
            consume(a.variable);
        } finally {
            a.lock.readLock().unlock();
        }
    }
}

推荐