zoukankan      html  css  js  c++  java
  • 使用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();
            }
    
        }
    }
  • 相关阅读:
    面试十题(4)
    TS中给接口指定的成员?
    TS中定义泛型接口的两种方式
    ts中泛型的使用
    ts中类的属性的封装
    ts中接口的使用
    自定义hook的步骤
    react中如何使用useReducer?
    react中useContext的使用
    react 中useRef的作用
  • 原文地址:https://www.cnblogs.com/moris5013/p/11827980.html
Copyright © 2011-2022 走看看