我有两个线程。一个调用修改变量的类的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...
}
}
Thanks,
AtomicInteger
类处理的整数操作。对于更复杂的操作,请查看synchronized
块或java.util.conccurent.locks.Lock
。 - justkt