1. 程式人生 > 其它 >實現自己的自旋鎖

實現自己的自旋鎖

public class MyLock {

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

     public static void myLock(){

         System.out.println(Thread.currentThread().getName() + "進來了");
         while (!atomicReference.compareAndSet(null,Thread.currentThread())){
             System.out.println(Thread.currentThread().getName() + "wait...");
         }
     }

     public static void myUnLock(){
         System.out.println(Thread.currentThread().getName() + "出去了");
         atomicReference.compareAndSet(Thread.currentThread(),null);
     }


    public static void main(String[] args) {
        new Thread(()->{
            myLock();
            try {
                TimeUnit.SECONDS.sleep(4);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
            myUnLock();
        },"a").start();

        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            myLock();
            System.out.println(Thread.currentThread().getName());
            myUnLock();
        },"b").start();
    }
}

a進來了
b進來了
bwait...
bwait...
bwait...
a出去了
bwait...
b
b出去了