根据我在互联网上阅读的一些文档,类似于
在第二行 (*), 虽然 T3 将
请有经验的人帮忙解答一下吗?
AtomicInteger
、AtomicLong
等类的变量只允许同时有1个线程访问它们。但是当我尝试使用AtomicBoolean
进行测试时,出现了问题。例如:public class TestAtomicBoolean {
public static void main(String[] args) {
final AtomicBoolean atomicBoolean = new AtomicBoolean(false);
new Thread("T1") {
@Override
public void run() {
while (true) {
System.out.println(Thread.currentThread().getName() + " is waiting for T3 set Atomic to true. Current is " + atomicBoolean.get());
if (atomicBoolean.compareAndSet(true, false)) {
System.out.println("Done. Atomic now is " + atomicBoolean.get());
break;
}
}
}
}.start();
new Thread("T2") {
@Override
public void run() {
while(true) {
System.out.println(Thread.currentThread().getName() + " " + atomicBoolean.get());
}
}
}.start();
new Thread("T3") {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " " + atomicBoolean.get());
System.out.println(Thread.currentThread().getName() + " is setting atomic to true");
atomicBoolean.set(true);
System.out.println(Thread.currentThread().getName() + " " + atomicBoolean.get());
}
}.start();
}
}
输出
T1 is waiting for T3 set Atomic to true. Current is false
T1 is waiting for T3 set Atomic to true. Current is false
T3 is setting atomic to true
T2 false
T3 true (*)
T1 is waiting for T3 set Atomic to true. Current is false (*)
T2 true
Done. Atomic now is false
T2 false
在第二行 (*), 虽然 T3 将
AtomicBoolean
设为 true,但之后 T1 读取的值是 false。所以,T1 和 T3 在同一时间访问了 AtomicBoolean
?我不理解 AtomicBoolean
的工作原理。请有经验的人帮忙解答一下吗?