1. 程式人生 > 其它 >自旋鎖

自旋鎖

技術標籤:併發程式設計

 private AtomicReference<Thread> atomicReference=new AtomicReference<>();

    public void mylock(){
        Thread thread=Thread.currentThread();
        System.out.println(Thread.currentThread().getName()+"come in");
       while (!atomicReference.compareAndSet
(null,thread)){ }; } public void myunlock(){ Thread thread=Thread.currentThread(); atomicReference.compareAndSet(thread,null); System.out.println(Thread.currentThread().getName()+"invoke myunlock"); } public static void main(String[] args) {
Spinlock spinlock=new Spinlock(); new Thread(()->{ spinlock.mylock(); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } spinlock.myunlock(); }
,"AA").start(); new Thread(()->{ spinlock.mylock(); spinlock.myunlock(); },"BB").start(); }