java内存模型
package com.itcast.jmm;
/**
* volatile可以保证线程可见性和有序性
*/
public class volatileTest {
// private static boolean flag = false;
private static volatile boolean flag = false;
public static void main(String[] args) throws InterruptedException {
new Thread(new Runnable() {
@Override
public void run() {
while (!flag) {
}
System.out.println("数据准备完毕,开始执行业务操作");
}
}).start();
Thread.sleep(2000);
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("数据开始准备");
flag = true;
System.out.println("数据准备完毕");
}
}).start();
Thread.sleep(Integer.MAX_VALUE);
}
}
数据开始准备
数据准备完毕
数据准备完毕,开始执行业务操作
package com.itcast.jmm;
/**
* volatile可以保证线程可见性和有序性,但是无法保证原子性
*/
public class AtomicTest {
private static volatile int num = 0;
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[10];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
for (int j = 0; j < 10000; j++) {
//这里必须使用Integer.class 全局锁对象(如果有synchronized的话,去掉volatile关键字也正确达到100000)
//这里不加锁,就会导致num结果小于100000
synchronized (Integer.class) {
num++;
}
}
}
});
threads[i].start();
}
//主线程等待全部子线程执行完,才结束
for (Thread thread : threads) {
thread.join();
}
System.out.println(num); //10*10000=100000
// Thread.sleep(Integer.MAX_VALUE);
}
}