Lock(锁)的使用 ReentrantLock
1. synchronized 与Lock的对比
-
Lock是显式锁(手动开启和关闭锁,别忘记关闭锁)synchronized是隐式锁,出了作用域自动释放。
-
Lock只有代码块锁,synchronized有代码块锁和方法锁
-
使用Lock锁,JVM将花费较少的时间来调度线程,性能更好。并且具有更好的扩展性(提供更多的子类)
-
优先使用顺序:
-
Lock >同步代码块(已经进入了方法体,分配了相应资源)>同步方法(在方法体之外)
2.lock锁的使用: private ReentrantLock lock = new ReentrantLock();
// 测试lock锁
public class TestLock {
public static void main(String[] args) {
TestLock2 testLock2 = new TestLock2();
new Thread(testLock2).start();
new Thread(testLock2).start();
new Thread(testLock2).start();
}
}
class TestLock2 implements Runnable{
int ticketNums = 10;
// 定义lock锁
private ReentrantLock lock = new ReentrantLock();