i++的原子性问题: i++的操作实际上分为三个步骤“读-改-写”
int i = 10;
i = i++; //此时i=10
i++操作可以拆成一下三步:
int temp = i;
i = i+1;
i = temp;
i++的原子性就要保证这三步一次执行完成。
package com.sheting.concurrent.atomicDemo;
/**
* Create Time: 2018-03-09 07:45
*
* @author sheting
*/
public class TestAtomicDemo {
public static void main(String[] args) {
AtomicDemo atomicDemo = new AtomicDemo();
for (int i = 0; i < 10; i++) {
new Thread(atomicDemo).start();
}
}
}
class AtomicDemo implements Runnable {
private int serialNumber = 0;
@Override
public void run() {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(getSerialNumber());
}
public int getSerialNumber() {
return serialNumber++;
}
}
执行结果:
代码说明:原子性问题不能用volatile修饰共享变量来解决,volatile只能保证共享变量的内存可见性。JDK1.5以后,在java.util.concurrent.atomic包下提供了常用的原子变量。
修改为原子变量保证原子性:
package com.sheting.concurrent.atomicDemo;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Create Time: 2018-03-09 07:45
*
* @author sheting
*/
public class TestAtomicDemo {
public static void main(String[] args) {
AtomicDemo atomicDemo = new AtomicDemo();
for (int i = 0; i < 10; i++) {
new Thread(atomicDemo).start();
}
}
}
class AtomicDemo implements Runnable {
//private int serialNumber = 0;
private AtomicInteger serialNumber = new AtomicInteger(0);
@Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(getSerialNumber());
}
public int getSerialNumber() {
// return serialNumber++;
return serialNumber.getAndIncrement();
}
}
原子变量通过 volatile和CAS算法保证数据的原子性。
例如 AtomicInteger 中 private volatile
int value;
CAS算法
CAS(Compare-And-Swap) 算法保证数据的原子性
CAS算法是硬件对于并发操作共享数据的支持
CAS包含三个操作数:
内存值 V
预估值 A
更新值 B
当且仅当 V==A时,V = B。 否则将不做任何操作。
CAS 是一种无锁的非阻塞算法的实现。
模拟CAS算法: 着是利用JVM去模拟,实际CAS是硬件层的算法
package com.sheting.concurrent.atomicDemo;
/**
* Create Time: 2018-03-09 09:22
*
* @author sheting
*/
public class TestCoompareAndSwap {
public static void main(String[] args) {
final CompareAndSwap cas = new CompareAndSwap();
for (int i = 0; i < 1000; i++) {
new Thread(new Runnable() {
@Override
public void run() {
int expectedValue = cas.get();
boolean b = cas.compareAndSet(expectedValue, (int) (Math.random() * 101));
System.out.println(b);
}
}).start();
}
}
}
class CompareAndSwap {
private int value;
//获取内存值
public synchronized int get() {
return value;
}
//比较
public synchronized int compareAndSwap(int expectedValue, int newValue) {
int oldValue = value;
if (oldValue == expectedValue) {
this.value = newValue;
}
return oldValue;
}
//设置
public synchronized boolean compareAndSet(int expectedValue, int newValue) {
return expectedValue == compareAndSwap(expectedValue, newValue);
}
}