手写Lock

public class SpinLockDemo {
    AtomicReference<Thread> atomicReference = new AtomicReference<>();
<pre><code>public void MyLock() {
    Thread thread = Thread.currentThread();
    System.out.println(thread.getName() + "Lock");
    //只有第一个拿到锁的线程可以不被while阻塞
    while (!atomicReference.compareAndSet(null,thread)) {  

    }
}

public void MyUnLock() {
    Thread thread = Thread.currentThread();
    System.out.println(thread.getName() + "UnLock");
    //释放锁,让其他线程争夺锁
    atomicReference.compareAndSet(thread,null);
}

}

使用范例

public class Client {
public static void main(String[] args) {
SpinLockDemo lock = new SpinLockDemo();
new Thread(() -> {
lock.MyLock();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.MyUnLock();
}
},"A").start();</p>
<pre><code>    new Thread(() -&gt; {
        lock.MyLock();
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.MyUnLock();
        }
    },"B").start();
}

}