可重入概念 不等同于 线程安全
http://baike.baidu.com/view/814104.htm
与syncronized类似,但是能够有更精细的控制,可以接受超时中断等待线程等其他特性。隐式锁一旦线程在获取锁的状态,是不能被中断的。
public boolean trySendOnSharedLine(String message,
long timeout, TimeUnit unit)
throws InterruptedException {
long nanosToLock = unit.toNanos(timeout)
- estimatedNanosToSend(message);
if (!lock.tryLock(nanosToLock, NANOSECONDS))
return false;
try { return sendOnSharedLine(message);
} finally {
lock.unlock();
}
}
public boolean sendOnSharedLine(String message) throws InterruptedException { lock.lockInterruptibly(); try { return cancellableSendOnSharedLine(message); } finally { lock.unlock(); }
}
private boolean cancellableSendOnSharedLine(String message)
throws InterruptedException { ... }
控制粒度精细,不再局限于一个结构化块状代码,例如hashmap里面对hash chain分别进行lock
除非需要使用到syncronized所不能提供的功能,否则尽量不要用ReentrantLock。
引用java并发编程实践(阅读关于ReentrantLock 章节)
ReentrantLock provides the same locking and memory semantics as intrinsic locking, as well as additional features such
as timed lock waits, interruptible lock waits, fairness(公平是需要损耗性能的), and the ability to implement non‐block‐structured locking
ReentrantLock is an advanced tool for situations where intrinsic locking is not practical. Use it if you need its advanced
features: timed, polled, or interruptible lock acquisition, fair queuing, or non‐block‐structured locking. Otherwise, prefer
synchronized.
当线程调用condition.wait的时候,当前线程持有的可重入锁会释放;当其他线程调用condition.signal的时候,该线程重新获得锁并复原。