说到 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();
}
}
结果如下: