采用AtomicInteger实现显示锁

利用了AtomicInteger的compareAndSet方法

public class CASLock {

    private  AtomicInteger value = new AtomicInteger();
    
    Thread  lockThread ;
    
    public boolean tryLock() {
        if(value.compareAndSet(0, 1)) {
            lockThread = Thread.currentThread();
            return true;
        }else {
            return false;
        }
    }
    
    public void unLock() {
        if(value.get() == 0) {
            return;
        }
        if(lockThread == Thread.currentThread()) {
            value.compareAndSet(1, 0);
        }
    }
}


public class CASLockTest {

    static CASLock lock = new CASLock();

    public static void main(String[] args) {

        IntStream.rangeClosed(1, 3).forEach(x -> {
            new Thread() {
                public void run() {
                    doSomething();
                }
            }.start();
        });
    }

    public static void doSomething() {
        try {
            if (lock.tryLock()) {
                System.out.println(Thread.currentThread().getName() + " get the lock ");
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                System.out.println(Thread.currentThread().getName() + " can not get the lock ");
            }
        } finally {
            lock.unLock();
        }

    }
}

猜你喜欢

转载自www.cnblogs.com/moris5013/p/11827980.html