java.util.concurrent.locks

Class ReentrantLock

All Implemented Interfaces: Serializable, Lock

A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.

也就是跟synchronized设计本意类似,都是用来实现同步的,只不过ReentrantLock还有更多的功能。

A ReentrantLock is owned by the thread last successfully locking, but not yet unlocking it.

Method:

1
2
3
4
5
6
7
8
9
boolean tryLock()

void lock()

void unlock()

protected Thread getOwner()

...


ReentrantLock: synchronized

Why use a ReentrantLock if one can use synchronized(this)?

stackoverflow

A ReentrantLock is unstructured, unlike synchronized constructs – i.e. you don’t need to use a block structure for locking and can even hold a lock across methods. An example:

1
2
3
4
5
6
7
8
9
10
11
12
13
private ReentrantLock lock;

public void foo() {
...
lock.lock();
...
}

public void bar() {
...
lock.unlock();
...
}

Aside from that, ReentrantLock supports lock polling and interruptible lock waits that support time-out. ReentrantLock also has support for configurable fairness policy, allowing more flexible thread scheduling.

More on StackOverflow.