码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA多线程---无锁

时间:2017-06-14 13:06:47      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:unsafe   private   zed   syn   自己的   不能   利用   and   date   

无锁是一种乐观策略,使用CAS(compare and swap)来鉴别线程冲突,如果发生冲突,就重试当前操作直到没有冲突为止。

CAS(V,E,N) V要更新的变量,E表示预期值,N表示心值

仅当V=E时,才会将V设置为N  如果V!=E 说明已经有其他线程做了更新 当前线程什么也不做

CAS操作即使没有锁,也可以发现其他线程对当前线程的干扰,并进行恰当的处理。


AtomicInteger

#final boolean compareAndSet(int expect, int u)  //如果当前值为expect 则设置为u

compareAndSet ----> unsafe.compareAndSwapInt(Objuect obj,long valueOffset,int expect,int update)    

不支持static字段  

其实CAS也算是有锁操作,只不过是由CPU来触发,比synchronized性能好的多。  ---http://www.jianshu.com/p/9f0ba2bab24e

自己的应用程序无法使用Unsafe类 它是一个JDK内部使用的专属类


AtomicReference //保证修改对象引用时线程安全性

AtomicStampedReference //应用于“一次修改”  此时不仅比对值 也要比对时间戳


 

AtomicIntegerArray  AtomicLongArray AtomicReferenceArray  


AtomicIntegerFieldUpdater

利用反射机制

变量需要定义为 volatile 且不能是private static 类型  

 

JAVA多线程---无锁

标签:unsafe   private   zed   syn   自己的   不能   利用   and   date   

原文地址:http://www.cnblogs.com/luyu1993/p/7007986.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!