自旋锁简单实现

package wetalk.build.threadSafe.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 自旋锁
 */
public class SpinLock {

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

    public void lock() {
        final Thread thread = Thread.currentThread();
        while (!atomicReference.compareAndSet(null, thread)) ;
    }

    public void unlock() {
        final Thread thread = Thread.currentThread();
        while (!atomicReference.compareAndSet(thread, null)) ;
    }

    public static void main(String[] args) {
        SpinLock spinLock = new SpinLock();
        new Thread(() -> {
            try {
                spinLock.lock();
                System.out.println("t1 start to execute");
                TimeUnit.SECONDS.sleep(50);
                System.out.println("t1 execute success");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                spinLock.unlock();
            }
        }, "t1").start();

        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            try {
                spinLock.lock();
                System.out.println("t2 start to execute");
                TimeUnit.SECONDS.sleep(10);
                System.out.println("t2 execute success");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                spinLock.unlock();
            }
        }, "t2").start();
    }
}

自旋锁简单实现

你可能感兴趣的:(笔记)