自旋锁:是指尝试获取锁的线程不会立刻阻塞,而是会采用循环的方式去获取锁,直到获取成功。
1.自旋锁的优点:
减少线程上下文切换的消耗
(如果不是自旋机制,那进来发现已经被加锁了,只能线程阻塞住了,只能等待CPU线程调度,在阻塞住,还没调度到其他线程的这段时间内,就是无用时间,也就是相当于线程白白被消耗,不做任何事,这样会降低程序的并发性)
2.自旋锁的缺点:
循环会消耗CUP(有时候运气就是不好,一直自旋比较,都不是期望的值,一直循环,所以会消耗CPU)
自己写个自旋锁,验证下
import java.util.concurrent.atomic.AtomicReference;
/**
* 自旋锁 测试
*/
public class SpinLockDemo {
//原子引用线程
AtomicReference<Thread> atomicReference = new AtomicReference<>();
public void myLock(){
Thread thread = Thread.currentThread();
System.out.println(Thread.currentThread().getName()+"\t come in");
while(!atomicReference.compareAndSet(null,thread)){
}
System.out.println(Thread.currentThread().getName()+"\t getLock");
}
public void myUnLock(){
Thread thread = Thread.currentThread();
atomicReference.compareAndSet(thread,null);
System.out.println(Thread.currentThread().getName()+"\t come out");
}
public static void main(String[] args) {
SpinLockDemo spinLockDemo = new SpinLockDemo();
new Thread(()->{
spinLockDemo.myLock();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
spinLockDemo.myUnLock();
},"AA").start();
new Thread(()->{
spinLockDemo.myLock();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
spinLockDemo.myUnLock();
},"BB").start();
}
}
结果
AA come in
BB come in
AA getLock
AA come out
BB getLock
BB come out
网友评论