自旋锁
自旋锁
是什么?
指尝试获取锁的线程不会立即阻塞,而是采取循环的方式去尝试获取锁,好处就是减少了上下文切换的消耗,缺点是会消耗CPU
/*
手写一个 自旋锁 (基于CAS)
*/
public class juc1{
//原子引用线程
AtomicReference atomicReference = new AtomicReference<Thread>();
public void mylock(){
Thread thread = Thread.currentThread();
System.out.println(thread.getName()+"come in ~~");
//不停尝试获取锁
//能放进去,就不走循环 放进去 方法返回了true,放进去不走循环加一个反
while (!atomicReference.compareAndSet(null,thread)){
}
}
public void myUnlock(){
Thread thread = Thread.currentThread();
System.out.println(thread.getName()+"\tunlock~~~");
//将当前线程
atomicReference.compareAndSet(thread,null);
}
public static void main(String[] args) throws InterruptedException {
juc1 juc1 = new juc1();
new Thread(()->{
juc1.mylock();
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
juc1.myUnlock();
},"t1").start();
//主线程睡1秒,保证t2在后面执行
TimeUnit.SECONDS.sleep(1);
new Thread(()->{
juc1.mylock();
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
juc1.myUnlock();
},"t2").start();
}
}
查看10道真题和解析