Lock
synchronized与Lock的区别
类别 | synchronized | Lock |
---|---|---|
结构 | Java关键字 | Java类 |
释放锁 | 等待已经获取锁的线程同步完代码后释放锁、线程发生异常,jvm让线程释放锁 | 在finally中释放锁,否则会造成线程死锁 |
获取锁 | 等待其他线程释放锁 | 可以尝试获取锁,不用一直等待 |
锁状态 | 无法判断 | 可以判断 |
锁类型 | 可重入、不可中断、非公平 | 可重入、可判断、可公平 |
性能 | 少量同步 | 大量同步 |
源码分析
public interface Lock {
/**
* Acquires the lock.
*/
void lock();
/**
* Acquires the lock unless the current thread is
* {@linkplain Thread#interrupt interrupted}.
*/
void lockInterruptibly() throws InterruptedException;
/**
* Acquires the lock only if it is free at the time of invocation.
*/
boolean tryLock();
/**
* Acquires the lock if it is free within the given waiting time and the
* current thread has not been {@linkplain Thread#interrupt interrupted}.
*/
boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
/**
* Releases the lock.
*/
void unlock();
/**
* Returns a new {@link Condition} instance that is bound to this
* {@code Lock} instance.
* @return A new {@link Condition} instance for this {@code Lock} instance
* @throws UnsupportedOperationException if this {@code Lock}
* implementation does not support conditions
*/
Condition newCondition();
}
- lock(): 获取锁,如果锁被占用则一直等待
- unlock():释放锁
- tryLock(): 获取锁时锁被占用返回false,否则true
- tryLock(long time, TimeUnit unit):增加一个等待时间
- lockInterruptibly():线程在获取锁的阶段进入等待,那么中断次线程,先去完成其他任务
- Condition newCondition():返回绑定到此 Lock 实例的新 Condition