CAS(锁)
在java世界里,为什么需要锁,因为多线程并发访问共享资源时会出错,出什么问题?
看例子
- public class domain(){
- private int num;
- public int addNUm(){
- return num++;
- }
- }
A线程和B线程同时在LOCK POOL (锁池)中 AB线程同时获得操作系统运行addNum()方法的时间片,开始时 A线程num==0,B线程num==0,A线程在CPU中时间片到了,B线程先执行
此时num==1,这是A线程有获得时间片了,A==1就会出错!
怎么解决?
- public calss domain(){
- private int num;
- public synchronized int addNun(){
- return num++;
- }
- }
加了synchronized,每次只能有一个线程获得这个资源,A进来后,会得到这个锁,B要进来必须要从A线程身上得到这个锁,避险了冲突,但是这样有一个弊端,
比如有10个线程,当一个进程获得锁时,其他九个线程都在 lock pool 中 ,很无聊 ,浪费资源,怎么办?
出现了CAS(campareAndSwap)什么意思?
A,B线程都从内存中拿到这个一个num变量,记为C,操作完后再拿C和内存中的变量比较 如果相等,则说明,A线程在操作的过程中 num变量没有被其他线程改动过,则直接替换掉内存中的变量,
- public class domain(){
- while(true){
- private int C=内存中的值;
- private int num = c+1;
- if(compareAndSwap(内存中的值,C,num)){
- reutrn num;
- }
- }
- }
java是面向对象的,以上过程会被封装起来,底层是C语言写的,比如
- public class domain(){
- private AromicInteger num = new AromicInteger(0);
- public int addNum(){
- while(rtue){
- int num= num.get();
- int num1 =num+1;
- if(compareAndSet(num,num1,)){
- return num1;
- }
- }
- }
- }