1、关于valitile对变量的可见性测试
package com.delicacy.oatmeal.java.volatiletest;
/**
* valitile dome
* volatile 关键字保证了操作的可见性
* valitie 最好用于一写多读的情况下
* {@link VolatileDemo2} 测试volatile不能保证对变量的操作是原子性
* @author zyt
* @create 2018-04-15 12:53
**/
public class VolatileDemo extends Thread{
private static boolean flag = false;
public void run() {
while (!flag){
};
System.out.println("停止了");
}
public static void main(String[] args) throws Exception {
new VolatileDemo().start();
new VolatileDemo().start();
new VolatileDemo().start();
System.out.println("当前flag是"+flag);
Thread.sleep(100);
flag = true;
System.out.println("当前flag是"+flag);
}
}
2、volatile不能保证对变量的操作是原子性
package com.delicacy.oatmeal.java.volatiletest;
import java.util.concurrent.CountDownLatch;
/**
* 测试volatile不能保证对变量的操作是原子性
*
* @author zyt
* @create 2018-04-15 12:53
**/
public class VolatileDemo2 extends Thread{
public volatile int inc = 0;
public /*synchronized*/ void increase() {
inc++;
}
public static void main(String[] args) {
process2();
}
private static void process1() {
final VolatileDemo2 test = new VolatileDemo2();
for(int i=0;i<10;i++){
new Thread(() -> {
for(int j=0;j<1000;j++)
test.increase();
}).start();
}
while(Thread.activeCount()>1)
Thread.yield();
System.out.println(test.inc);
}
private static void process2() {
final int count = 10;
final CountDownLatch latch = new CountDownLatch(count);
final VolatileDemo2 test = new VolatileDemo2();
for(int i=0; i<count; i++){
new Thread(()->{
for(int j=0;j<1000;j++){
test.increase();
}
latch.countDown();
}).start();
}
try {
latch.await();
} catch (InterruptedException e) {
}
System.out.println(test.inc);
}
private static void process3() {
final VolatileDemo2 test = new VolatileDemo2();
Thread thread = new Thread(() -> {
for (int j = 0; j < 1000; j++)
test.increase();
});
Thread thread2 = new Thread(() -> {
for (int j = 0; j < 1000; j++)
test.increase();
});
thread.start();
thread2.start();
try {
thread.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(test.inc);
}
}