ReentrantLock
是一个可重入独占锁。可重入的意思是同一个线程可以对同一个共享资源进行重复的加锁和释放锁;独占锁就是任何时刻只允许一个线程占有锁。
如下例子是两个线程交互获得锁:
public class ReentrantLockDemo implements Runnable {
//参数true,表示这是一个公平锁
private static ReentrantLock lock = new ReentrantLock(true);
@Override
public void run() {
while (true){
try {
//acquire lock
lock.lock();
System.out.println(Thread.currentThread().getName() + " acquire a lock success");
Thread.sleep(1000);
}catch (Exception e){
e.printStackTrace();
}finally {
//release lock
lock.unlock();
}
}
}
public static void main(String[] args) {
ReentrantLockDemo reentrantLockDemo = new ReentrantLockDemo();
Thread thread1 = new Thread(reentrantLockDemo,"thread1");
Thread thread2 = new Thread(reentrantLockDemo,"thread2");
thread1.start();
thread2.start();
}
}
如下输出结果:thread1
和thread2
轮流获得锁,注意如果ReentrantLock
不是公平锁,那么可能会存在某个线程一直获取不到锁。
thread1 acquire a lock success
thread2 acquire a lock success
thread1 acquire a lock success
thread2 acquire a lock success
....