原 java 自旋锁
版权声明:本文为博主原创文章,请尊重他人的劳动成果,转载请附上原文出处链接和本声明。
本文链接:https://www.91mszl.com/zhangwuji/article/details/1135
自旋锁(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
博主信息