Java并发编程七CAS自旋锁

编程

public class CASLockUtil {

public static AtomicReference casLock = new AtomicReference<Thread>();

/**

* 加锁

* @param waitMillis 重试时间,如果超过这个时间则放弃当前的锁Millis

* @return

*/

public static boolean lock(long waitMillis){

long end = System.currentTimeMillis()+waitMillis;

boolean isLock = casLock.compareAndSet(null,Thread.currentThread());

while (!isLock&&end> System.currentTimeMillis()){

isLock = casLock.compareAndSet(null,Thread.currentThread());

}

//如果是0就无限尝试

while (waitMillis==0&&!isLock){

isLock = casLock.compareAndSet(null,Thread.currentThread());

}

return isLock;

}

/**

* //解锁

* @return

*/

public static boolean unLock(){

boolean isLock = casLock.compareAndSet(Thread.currentThread(),null);

return isLock;

}

public static void main(String[] args) {

new Thread(new Runnable() {

@Override

public void run() {

try {

boolean isLock = CASLockUtil.lock(1000);

if(isLock){

System.out.println("线程1拿到锁休眠10秒");

Thread.sleep(10000);

}else {

System.out.println("线程1没有拿到锁");

}

}catch (Exception e){

}finally {

CASLockUtil.unLock();

}

}

}).start();

new Thread(new Runnable() {

@Override

public void run() {

try {

boolean isLock = CASLockUtil.lock(0);

if(isLock){

System.out.println("线程2拿到锁休眠10秒");

Thread.sleep(10000);

}else {

System.out.println("线程2没有拿到锁");

}

}catch (Exception e){

}finally {

CASLockUtil.unLock();

}

}

}).start();

}

}

利用AtomicReference的compareAndSet对当前线程对象进行加锁。测试结果

线程1拿到锁休眠10秒
线程2拿到锁休眠10秒

 

以上是 Java并发编程七CAS自旋锁 的全部内容, 来源链接: utcz.com/z/517493.html

回到顶部