自旋锁就是在对资源进行获取时,资源已经被占用,无法立即获取,所以一直自旋,循环尝试获取锁,等到其它线程将锁释放,才会获得锁。
代码写一个自旋锁
public class Zixuansuo {
AtomicReference<Thread> atomicReference = new AtomicReference();
//加锁
public void dolock(){
Thread thread = Thread.currentThread();
while (!atomicReference.compareAndSet(null,thread)){
}
System.out.println(thread.getName()+"=》"+"上锁了");
}
//解锁
public void unlock(){
Thread thread = Thread.currentThread();
atomicReference.compareAndSet(thread,null);
System.out.println(thread.getName()+"=》"+"解锁了");
}
}
测试类
class TestZXS{
public static void main(String[] args) throws InterruptedException {
Zixuansuo zixuansuo = new Zixuansuo();
new Thread(new Runnable() {
@Override
public void run() {
zixuansuo.dolock();
try {
TimeUnit.SECONDS.sleep(5);
}catch (Exception e){
e.printStackTrace();
}finally {
zixuansuo.unlock();
}
}
},"a").start();
TimeUnit.SECONDS.sleep(1);
new Thread(new Runnable() {
@Override
public void run() {
zixuansuo.dolock();
try {
TimeUnit.SECONDS.sleep(1);
}catch (Exception e){
e.printStackTrace();
}finally {
zixuansuo.unlock();
}
}
},"b").start();
}
}
执行结果:
a=》上锁了
a=》解锁了
b=》上锁了
b=》解锁了