手写实现一个可重入锁!

版权声明:转载请注明出处http://write.blog.csdn.net/postlist https://blog.csdn.net/z_565282532/article/details/78943821

代码如下:

public class MyLock implements Lock{
    Thread lockBy = null;
    int lockCount = 0;
    //锁标志 
    private boolean isLocked = false;
    /*
     * 加锁
     * (non-Javadoc)
     * @see java.util.concurrent.locks.Lock#lock()
     */
    @Override
    public synchronized void lock() {
        Thread currentThread = Thread.currentThread();

        //如果不是第一个进来,则在这儿等待
        while (isLocked && currentThread != lockBy) {
            // ...阻塞到这儿,都等待,但是第一个进来不让让等待
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        //如果是第一个进来,将其变为false
        isLocked = true;
        //将lockBy指向当前线程
        lockBy = currentThread;
        //计数器自增
        lockCount ++;
    }

    /*
     * 释放锁
     * (non-Javadoc)
     * @see java.util.concurrent.locks.Lock#lockInterruptibly()
     */
    @Override
    public synchronized void unlock() {
        //如果当前线程等于lockBy
        if (lockBy == Thread.currentThread()) {
            lockCount --;
            if (lockCount == 0) {
                notify();
                //释放锁
                isLocked =false;
            }
        }
    }
    @Override
    public void lockInterruptibly() throws InterruptedException {


    }

    @Override
    public boolean tryLock() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public Condition newCondition() {
        // TODO Auto-generated method stub
        return null;
    }

}

测试类:

public class Sequence {
    private MyLock lock = new MyLock();

    public void method1() {
        lock.lock();
        System.out.println("method1");
        method2();
        lock.unlock();

    }

    public void method2() {
        lock.lock();
        System.out.println("method2");
        lock.unlock();
    }
    public static void main(String[] args) {
        Sequence s = new Sequence();
        new Thread(() -> s.method1()).start();
    }


}
展开阅读全文

没有更多推荐了,返回首页