public static void main(String[] args) {
final RedisPool.TestThread testThread1 = new RedisPool.TestThread();
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
testThread1.test1();
}
},"thread1");
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
testThread1.test2();
}
},"thread2");
thread1.start();
thread2.start();
}
private static class TestThread{
private volatile int count = 0;
public void test1() {
for (int i = 0; i < 10; i++) {
try {
TimeUnit.MICROSECONDS.sleep(300000);
} catch (InterruptedException e) {
e.printStackTrace();
}
count+=3;
System.out.println(Thread.currentThread().getName()+" test1 "+i+" count "+count);
}
}
public void test2() {
for (int i = 0; i < 10; i++) {
try {
TimeUnit.MICROSECONDS.sleep(300000);
} catch (InterruptedException e) {
e.printStackTrace();
}
count-=3;
System.out.println(Thread.currentThread().getName()+" test2 "+i+" count "+count);
}
}
}
最后的count并不为零。
Java提供了volatile关键字来保证可见性、有序性。但不保证原子性。
c+=3,可以拆分成三部,读取c,加3,写回内存。线程1对变量进行自增操作,线程1先读取了变量count的原始值,然后线程1被阻塞了;然后线程2对变量进行自增操作,线程2也去读取变量count的原始值,由于线程1只是对变量count进行读取操作,而没有对变量进行修改操作,所以不会导致线程2的工作内存中缓存变量count的缓存行无效,所以线程2会直接去主存读取count的值,发现count的值时0,然后进行减3操作,并把-3写入工作内存,最后写入主存。
总结:自增操作是三个原子操作组合而成的复合操作。在一个操作中,读取了count变量后,是不会再读取的count的,所以它的值还是之前读的,它的下一步是自增操作,volatile能保证在读和写入主存时候的原子性,但并不能保证整个复合运算过程(读,运算,写)的 原子性。