实现可重入锁以及Lock的相关理解

2020.01.14

  • 可重入锁的实现
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class MyLock implements Lock {

    private boolean isLocked = false;

    private Thread threadName = null;

    private int currentCount = 0;

    @Override
    public synchronized void lock() {

        while (isLocked && threadName != Thread.currentThread()){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        isLocked = true;
        threadName = Thread.currentThread();
        currentCount ++;
    }

    @Override
    public synchronized void unlock() {
        if(threadName == Thread.currentThread()){
            currentCount --;

            if(currentCount == 0){
                isLocked = false;
                notify();
            }
        }
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
  • 关于Lock
    (1)Lock需要显示地获取和释放锁,繁琐但是灵活,例如在当一个锁锁住时,可以手动的释放另一个锁
    (2)使用Lock可以方便的实现公平性
    (3)相当于是Synchronized的一个包装
    (4)非阻塞的获取锁,例如tryLock
    (5)获取锁的时候能被中断
    (6)超时获取锁,例如设置时间获取锁

  • 关于Synchronized
    Synchronized不需要显示地获取和释放锁,简单但是套路固定,如果不是非常复杂的获取锁,Synchronized是个不错的选择

你可能感兴趣的:(Diary,多线程,java)