并发编程中的原子性问题
测试:20个线程对一个普通int变量进行++操作。
package pers.zhang.juc.part1;
/**
* @author zhang
* @date 2020/1/16 - 17:52
*
* 并发编程中的原子性问题
*/
public class TestAtomicDemo {
public static void main(String[] args) {
AtomicDemo ad = new AtomicDemo();
for(int i = 0; i < 20; i++){
new Thread(ad,"thread" + i).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(Thread.currentThread().getName() + ":" + getSerialNumber());
}
public int getSerialNumber(){
return serialNumber++;
}
}
输出:
thread0:0
thread1:1
thread5:2
thread12:8
thread9:11
thread10:10
thread11:9
thread13:7
thread14:6
thread4:5
thread2:3 //重复
thread3:4
thread6:3 //重复
thread8:12 //重复
thread7:12 //重复
thread19:13
thread18:14
thread17:15
thread16:16
thread15:17
分析: 是否是由于内存的可见性问题引起的?
测试: 使用volatile关键字声明变量
private volatile int serialNumber = 0;
输出:
thread0:0
thread1:1
thread4:2
thread2:3
thread3:4
thread5:5
thread6:6
thread7:7
thread8:8
thread9:9
thread10:10
thread11:11
thread12:12
thread17:14 //重复
thread18:14 //重复
thread19:13
thread16:15
thread15:16
thread14:17
thread13:18
再次分析: volatile解决了内存可见性问题,但是程序依然错误。由此引出了并发编程中的原子性问题。
在Java中,i++ 操作的底层是这样实现的:
_temp = i;
i = i + 1;
i = _temp;
换一种写法:j = i++;
_temp = i;
i = i + 1;
j = _temp;
可以看出,i++操作并不是一蹴而就的,它是分为几步执行。所以就导致了在多线程环境中,类似i++的非原子性操作出错。
解决: 使用jdk5 以后java.util.concurrent.atomic包下的原子变量
- volatile保证内存可见性
- CAS(Compare-And-Swap)算法保证数据的原子性
CAS算法
CAS是一种硬件对并发的支持,针对多处理器操作而设计的处理器中的一种特殊指令,用于管理对共享数据的并发访问。
CAS是一种无锁的非阻塞算法的实现
CAS包含了3个操作数:
- 需要读写的内存值V
- 进行比较的值A
- 拟写入的新值B
当且仅当V的值等于A时,CAS通过原子方式用新值B来更新V的值,否则不会执行任何操作。
原子变量
-
类的小工具包,支持在单个变量上解除锁的线程安全编程。事实上,此包中的类可将volatile值、字段和数组元素的概念扩展到哪些也提供原子条件更新操作的类。
-
类AtomicBoolean、AtomicInteger、AtomicLong和AtomicReference的实例各自提供对相应类型单个变量的访问和更新。每个类也为该类型提供适当的实用工具方法。
-
AtomicIntegerArray、AtomicLongArray和AtomicReferenceArray类进一步扩展了原子操作,对这些类型的数组提供了支持。这些类在为数组元素提供volatile访问语义方面也引人注目,这对于普通数组来说是不受支持的。
核心方法:boolean compareAndSet(expectedValue, updateVlue)
改正上面的示例程序
package pers.zhang.juc.part1;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author zhang
* @date 2020/1/16 - 17:52
*
* 并发编程中的原子性问题
*/
public class TestAtomicDemo {
public static void main(String[] args) {
AtomicDemo ad = new AtomicDemo();
for(int i = 0; i < 20; i++){
new Thread(ad,"thread" + i).start();
}
}
}
class AtomicDemo implements Runnable{
private volatile AtomicInteger serialNumber = new AtomicInteger(0);
@Override
public void run() {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":" + getSerialNumber());
}
public int getSerialNumber(){
return serialNumber.getAndIncrement();//获取并自增
}
}
输出:
thread1:2
thread3:3
thread0:1
thread2:0
thread4:4
thread5:5
thread6:6
thread7:7
thread9:8
thread8:9
thread12:10
thread11:11
thread10:12
thread13:13
thread19:15
thread15:18
thread14:19
thread16:17
thread18:16
thread17:14