JMM :
八大操作:
lock、unlock; read、load;use、assign; store、write;store、write。
1.保证可见性(JMM)
2.不保证原子性(原子性)
3.禁止指令重排(单列模式、 CAS )
public class Demo01 {
// private static int num = 0;
private volatile static int num = 0;// volatile 保证可见性
public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
while (num == 0) {
}
}).start();
TimeUnit.SECONDS.sleep(1);
num = 1;//虽然main线程修改了这个值,但是上面线程并不知道
System.out.println(num);
}
}
public class Demo02 {
public volatile static AtomicInteger num = new AtomicInteger();
// public volatile static num = 0;
//synchronized
public static void add() {
//num++;不是原子性
num.getAndIncrement();
}
public static void main(Strin在这里插入代码片g[] args) {
//期望值 2万
for (int i = 0; i < 20; i++) {
new Thread(() -> {
for (int j = 0; j < 1000; j++) {
add();
}
}, String.valueOf(i)).start();
}
//判断线程活着数量
while (Thread.activeCount() > 2) {
Thread.yield();
}
System.out.println(Thread.currentThread().getName() + " " + num);
}
}
//问题:不要synchronized和lock,怎么保证多线程原子性。