美文网首页
synchronized和lock

synchronized和lock

作者: MisAutumn | 来源:发表于2020-06-15 16:05 被阅读0次
- synchronized Lock
存在 jvm关键字 是一个类
锁状态 不可判断 可判断
锁类型 非公平,可重入,不可中断 可设置成公平锁,可重入,可中断
锁释放 执行完自动释放,遇到异常jvm释放,不会死锁 手动释放
- 阻塞时会一直等待 可设置等待时间

非公平锁:维护一个队列存储线程,一个线程入队之前先争抢锁,没抢到才被加入队列
公平锁:所有新来的线程加在队列尾部

public interface Lock {
  // 获取锁
    void lock();
    boolean tryLock();  // 无论是否拿到锁都会立即返回
    boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
  // 释放锁
    void unlock();     
    Condition newCondition();
    void lockInterruptibly() throws InterruptedException;
}

Lock必须在try{} catch{}中进行,并且将释放锁的操作放在finally{}中进行,以保证锁一定被被释放,防止死锁的发生。
lock.lockInterruptibly()会让没有拿到锁的线程调用t.interrupt()中断,但已经拿到锁的线程是无法被t.interrupt()中断的。

ReentrantLock

isFair()       //判断锁是否是公平锁
isLocked()     //判断锁是否被任何线程获取了
isHeldByCurrentThread() //判断锁是否被当前线程获取了
hasQueuedThreads()      //判断是否有线程在等待该锁

ReadWriteLock

将读写锁分开交给线程.
如果A线程已经占用了读锁,则申请写锁的线程会一直等待A释放读锁。
如果A线程已经占用了写锁,则此时其他申请写锁或读锁的线程会一直等待A释放写锁。

public interface ReadWriteLock {
    /**
     * Returns the lock used for reading.
     * @return the lock used for reading.
     */
    Lock readLock();
    /**
     * Returns the lock used for writing.
     * @return the lock used for writing.
     */
    Lock writeLock();
}

参考

相关文章

网友评论

      本文标题:synchronized和lock

      本文链接:https://www.haomeiwen.com/subject/aljgzhtx.html