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...
}
}
谢谢