synchronized 与 Lock 的区别:
- synchronized是内置的Java关键字;Lock是一个Java类。
- synchronized无法判断锁的状态;Lock可以判断是否获取到了锁。
- synchronized会自动释放锁;Lock必须手动释放锁,如果不释放,会造成死锁!
- synchronized线程1(获得锁,阻塞)、线程2(等待,傻傻的等);Lock不一定会一直等待下去(trylock)。
- synchronized是可重入锁、非公平、不可以中断的;Lock可重入锁、非公平(可以通过标志位设置)。
- synchronized适合锁少量的代码同步问题;Lock适合锁大量的代码同步问题。
说到 Lock 就不得不说 Condition ,官方文档中关于Condition的解释:
Lock -> synchronized
Condition.await() -> Object.wait()
Condition.signalAll() -> Object.notifyAll();
代码实现:
通过Condition进行精准的通知和唤醒:
// 资源类 判断等待 -> 业务 -> 通知
class Data{
private int number = 1;
Lock lock = new ReentrantLock();
Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
Condition condition3 = lock.newCondition();
public void printA() throws InterruptedException {
lock.lock();
try {
// 业务代码
while (number != 1) {
// 等待
condition1.await();
}
System.out.println(Thread.currentThread().getName() + " -> " + number);
number = 2;
// 通知其他线程
condition2.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void printB() throws InterruptedException {
lock.lock();
try {
while (number != 2) {
// 等待
condition2.await();
}
System.out.println(Thread.currentThread().getName() + " -> " + number);
number = 3;
// 通知其他线程
condition3.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void printC() throws InterruptedException {
lock.lock();
try {
while(number != 3){
// 等待
condition3.await();
}
System.out.println(Thread.currentThread().getName() + " -> " + number);
number = 1;
// 通知其他线程
condition1.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
// main方法
public class A {
public static void main(String[] args) {
Data data = new Data();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
data.printA();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "A").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
data.printB();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "B").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
data.printC();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "C").start();
}
}
结果如下: