【发布时间】:2010-08-16 13:49:58
【问题描述】:
我有两个线程。调用修改变量的类的更新方法。另一个调用读取变量的类的更新方法。只有一个线程写入,一个(或多个)线程读取该变量。由于我是多线程新手,在并发方面我需要做什么?
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...
}
}
谢谢,
【问题讨论】:
-
下面的许多答案都假设您正在执行可以由
AtomicInteger类处理的整数操作。对于更复杂的内容,请查看synchronized块或java.util.conccurent.locks.Lock
标签: java multithreading concurrency