• 实现一个可重入锁和不可重入锁


    可重入锁,持有锁的线程可以进入任何锁所同步的代码块

    不可重入锁:

    public class Lock {
        private boolean isLock = false;
    
        /**
         * 同步方法
         */
        public synchronized void lock() throws InterruptedException {
            if (isLock) {
                wait();
            }
            isLock = true;
        }
    
        // 不能保证我加的锁是我释放的,也就是不能保证一致性
        public synchronized void unLock() {
            isLock = false;
            notify();
        }
    
    }

    可重入锁

    public class Lock {
     
        private boolean isLock = false;
        private Thread lockedThread;
        private int lockCount;
    
        public synchronized void lock() throws InterruptedException {
            Thread currentThread = Thread.currentThread();
            while (isLock && lockedThread != currentThread) {
                wait();
            }
            isLock = true;
            lockedThread = currentThread;
            lockCount++;
        }
    
        public synchronized void unLock() {
            Thread currentThread = Thread.currentThread();
            // 我的锁只能我来释放,一致性
            if (lockedThread == currentThread) {
                lockCount--;
                if (lockCount == 0) {
                    isLock = false;
                    lockedThread = null;
                }
                notify();
            }
        }

    测试:

    public class LockTest {
        private Lock lock = new Lock();
    
        private void lockMethod1() throws InterruptedException {
            lock.lock();
            // 进入当前锁所同步的代码块,可重入锁不用等待直接获取锁,不可重入锁需要重新获取锁
            lockMethod2();
            lock.unLock();
        }
    
        private void lockMethod2() throws InterruptedException {
            lock.lock();
            // doSomeThing
            lock.unLock();
        }
    }
     
  • 相关阅读:
    选修课作业专栏
    js字符串和数组方法总结
    转Y-slow23原则(雅虎)
    前端优化总结和技巧(原创)
    阿里dom操作题
    基本的dom操作方法
    html5中的postMessage解决跨域问题
    mark一篇文章--用nodejs搭建一个本地反向代理环境
    html5语义化标签总结二
    转html5语义化标签总结一
  • 原文地址:https://www.cnblogs.com/yangyongjie/p/10614956.html
Copyright © 2020-2023  润新知