当前位置:   article > 正文

java-15种锁之自旋锁_java自旋锁有哪些

java自旋锁有哪些

1、Java自旋锁理论


自旋锁(spinlock):是指尝试去获取锁的线程不会立即阻塞,而是采用循环的方式去获取锁,这样的好处是减少线程上下文切换消耗,缺点是循环会消耗CPU。   (等待的时候还可以去处理其他任务)

  1.  public final int getAndAddInt(Object var1, long var2, int var4) {
  2.         int var5;
  3.         do {
  4.             var5 = this.getIntVolatile(var1, var2);
  5.         } while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));
  6.         return var5;
  7. }

2、手写自旋锁


 

  1. public class SpinlockDemo {
  2.        // AtomicReference对象创建初始值为null
  3.     private AtomicReference<Thread> threadAtomicReference = new AtomicReference<>();
  4.     public void lock() {
  5.         Thread currentThread  = Thread.currentThread();
  6.               // 模拟自旋
  7.         while(!threadAtomicReference.compareAndSet(null,currentThread)) {
  8.         }
  9.         System.out.println(Thread.currentThread().getName()+"\t get lock");
  10.     }
  11.     public void unLock(){
  12.         Thread currentThread  = Thread.currentThread();
  13.         threadAtomicReference.compareAndSet(currentThread,null);
  14.         System.out.println(Thread.currentThread().getName()+"\t release lock");
  15.     }
  16.     public static void main(String[] args) {
  17.         SpinlockDemo spinlockDemo = new SpinlockDemo();
  18.         // T1线程使用自旋方式获取锁,然后模拟5s业务处理
  19.         new Thread(()-> {
  20.             spinlockDemo.lock();
  21.             try {
  22.                 System.out.println(Thread.currentThread().getName()+"\t开始模拟5s业务处理");
  23.                 TimeUnit.SECONDS.sleep(5);
  24.                 System.out.println(Thread.currentThread().getName()+"\t模拟5s业务处理完毕");
  25.             } catch (InterruptedException e) {
  26.                 e.printStackTrace();
  27.             }
  28.             spinlockDemo.unLock();
  29.         },"T1").start();
  30.         // T1线程使用自旋方式获取锁,然后模拟3s业务处理
  31.         new Thread(()-> {
  32.             spinlockDemo.lock();
  33.             try {
  34.                 System.out.println(Thread.currentThread().getName()+"\t开始模拟5s业务处理");
  35.                 TimeUnit.SECONDS.sleep(5);
  36.                 System.out.println(Thread.currentThread().getName()+"\t模拟5s业务处理完毕");
  37.             } catch (InterruptedException e) {
  38.                 e.printStackTrace();
  39.             }
  40.             spinlockDemo.unLock();
  41.         },"T2").start();
  42.     }
  43. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/560645
推荐阅读
相关标签
  

闽ICP备14008679号