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();
            }
    
        }
    }
  • 相关阅读:
    学习进度第三周
    四则运算3
    学习进度第二周
    单元测试
    四则运算2
    学习进度第一周
    四则运算1
    构建之法阅读笔记01
    linux: 讨论一下网络字节序--------大端与小端的差别
    linux编程:线程条件同步
  • 原文地址:https://www.cnblogs.com/moris5013/p/11827980.html
Copyright © 2011-2022 走看看