package fangfa;
import java.util.concurrent.CountDownLatch;
public class Ljsdjj24324 {
public static void main(String[] args) throws InterruptedException {
Hasdy hasdy = new Hasdy();
CountDownLatch countDownLatch = new CountDownLatch(9999);
for (int i = 0; i < 9999; i++) {
new Thread(()->{
for (int i1 = 0; i1 < 100; i1++) {
hasdy.setaaa();
}
countDownLatch.countDown();
}).start();
}
countDownLatch.await();
Thread.sleep(5000);
System.out.println(hasdy.getasd());
}
}
class Hasdy{
volatile int a = 1;
void setaaa(){
a+=1;
}
int getasd(){
return a;
}
}
volatile并没有保证多线程安全
为什么会这样。
根据Happens-Before规则,先开启的线程对数据的修改对后续线程应该是可见的啊
难道是我理解错了吗?