关于Atomicboolean在并发访问完成时的奇怪行为的问题
我得到了这样的代码:
public class ConcurrencyCheck {
private volatile static AtomicBoolean top=new AtomicBoolean(false);
private int i=0;
public class Toppler extends Thread{
private final boolean bool;
public Toppler(boolean myBool,String name) {
super(name);
bool=myBool;
}
@Override
public void run() {
while(!isInterrupted()){
i++;
synchronized (top) {
if (top.get() == bool) top.set(!top.get());
System.err.println(super.getName() + " "+ bool +"->" + top + ". i is " + i);
}
try {
sleep(100);
} catch (InterruptedException e) {
break;
}
}
}
}
public static void main(String[] args) throws InterruptedException {
ConcurrencyCheck cc = new ConcurrencyCheck();
Thread t1= cc.new Toppler(true,"thread1");
Thread t2= cc.new Toppler(false,"thread2");
Thread t3= cc.new Toppler(true,"thread3");
Thread t4= cc.new Toppler(false,"thread4");
Thread t5= cc.new Toppler(true,"thread5");
Thread t6= cc.new Toppler(false,"thread6");
Thread t7= cc.new Toppler(true,"thread7");
Thread t8= cc.new Toppler(false,"thread8");
t1.start();
...
t8.start();
sleep(950);
t1.interrupt();
...
t8.interrupt();
}
}
它旨在检查 AtomicBoolean 的工作方式。Toppler 类是一个线程,它会定期推翻 Atomic 布尔值。推翻布尔值的代码块是同步的。正如我猜测的那样,每个输出行都必须推翻“top”变量的值,因此输出必须是“true->false false->true true->false...”。但出于某种原因,有时我可以看到这样的输出:
thread1 true->false. i is 1
thread8 false->true. i is 8
thread7 true->false. i is 8
thread4 false->true. i is 8
thread6 false->true. i is 8
thread3 true->false. i is 8
thread5 true->false. i is 8
thread2 false->true. i is 8
thread1 true->false. i is 9
thread8 false->true. i is 10
thread7 true->false. i is 11
thread4 false->true. i is 12
thread6 false->true. i is 13
thread3 true->false. i is 14
问题是:为什么可能出现两个随后的 false->true 或 true->false 输出行?