91名师指路-头部
91名师指路

java 自旋锁

由于某些原因,现在不支持支付宝支付,如需要购买源码请加博主微信进行购买,微信号:13248254750

自旋锁(spinlock):

是指尝试获取锁的线程不会立即阻塞,而是采用循环的方式去尝试获取锁,这样的好处是减少线程上下文切换的消耗,缺点是循环会消耗CPU。


手写一个自旋锁的代码如下:

package com.mszl.thread;

import java.util.concurrent.atomic.AtomicReference;

/**
* 功能:手写一个自旋锁
* 备注:更多资料请访问 http://www.91mszl.com
* @author bobo teacher
*/
public class SpinLockDemo {

AtomicReference<Integer> rf=new AtomicReference<Integer>(10);

public void myLock(){
Thread t=Thread.currentThread();
System.out.println(t.getName() + " myLock ");
while(!rf.compareAndSet(10, 80)){

}
}

public void myUnLock(){
Thread t=Thread.currentThread();
boolean flag=rf.compareAndSet(80, 10);
System.out.println(t.getName() + " myUnLock ");
}

public static void main(String[] args) {
SpinLockDemo sk=new SpinLockDemo();

Thread t1=new Thread(new Runnable() {
@Override
public void run() {
sk.myLock();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
sk.myUnLock();
}
});
t1.start();

try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}

Thread t2=new Thread(new Runnable() {
@Override
public void run() {
sk.myLock();

sk.myUnLock();
}
});
t2.start();
}


}


执行结果:

Thread-0 myLock 
Thread-0 myUnLock
Thread-1 myLock
Thread-1 myUnLock


2019-11-27 16:07:44     阅读(952)

名师出品,必属精品    https://www.91mszl.com

联系博主    
用户登录遮罩层
x

账号登录

91名师指路-底部