1、ReentrantLock
是互斥锁,基于AQS的互斥模式实现,也就是说同时只有一个线程进入临界区,唤醒下一个线程时也只能释放一个等待线程
AQS:AbstractQueuedSynchronizer (队列同步器)
AQS使用一个int类型的成员变量state来表示同步状态,当state>0时表示已经获取了锁,当state = 0时表示
释放了锁。它提供了三个方法(getState()、setState(int newState)、compareAndSetState(int expect,int update))来对同步状态state进行操作,当然AQS可以确保对state的操作是安全的。
通常通过如下代码块,来使用ReenntrantLock保护代码块:
Lock lock = new ReentrantLock();lock.lock();try {// update object state}finally {lock.unlock(); ####一定要在finally中进行锁的释放}
2、java多线程中Object.wait()和Condition.await()是否会释放当前线程锁占有的锁?
得到的结论是会释放:
A monitor is a collection of procedures, variables, and data
structures that are all grouped together in a special kind of module
or package. Processes may call the procedures in a monitor whenever
they want to, but they cannot directly access the monitor's internal
data structures from procedures declared outside the monitor. This
rule, which is common in modern object-oriented languages such as
Java, was relatively unusual for its time, although objects can be
traced back to Simula 67.
Condition的使用:
ArrayBlockingQueue内部,维护了一个定长数组,以便缓存队列中的数据对象,这是一个常用的阻塞队列,除了一个定长数组外,ArrayBlockingQueue内部还保存着两个整型变量,分别标识着队列的头部和尾部在数组中的位置。