做一个实验,期待发生bug,为啥却始终看不到?
场景:有n个红包放在数组中用false表示,有m个线程来抢,抢完设置true
期待错误:判断是false,就执行设置true。期待同时有多个线程判断了false,但只有一个设置成功,最终因为线程不够,数组中仍剩下false
结果:每次运行都是n个true
public class MyVolatile {
private volatile static boolean[] account;
public static void main(String[] args) {
//1 init
account = new boolean[50];
// Arrays.fill(account, false);默认初始化为假
//2 iterate
ArrayList<Thread> arrayList = new ArrayList<Thread>();
for (int i = 0; i < 52; i++) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
for (int j = 0; j < account.length; j++) {
if (account[j] == false) {
account[j] = true;
System.out.println("yes");
return;
}
}
System.out.println("no --- "+Thread.currentThread());
}
});
arrayList.add(thread);
}
for (Thread thread : arrayList) {
thread.start();
}
//3 end
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int total = 0;
for(int j=0; j<50; j++){
total += account[j] ? 1 : 0;
}
System.out.println("finally:" + total );
}
}