public class PessimisticLock {
private static ReentrantLock lock = new ReentrantLock();
private static Condition cA = lock.newCondition();
private static Condition cB = lock.newCondition();
private static Condition cC = lock.newCondition();
private static CountDownLatch latchB = new CountDownLatch(1);
private static CountDownLatch latchC = new CountDownLatch(1);
public static void main(String[] args) {
Thread threadA = new Thread(() -> {
lock.lock();
try {
for (int i = 0; i < 10; i++) {
System.out.print("A");
// 叫醒b
cB.signal();
if (i == 0) {
latchB.countDown();
}
cA.await();
}
cB.signal();
} catch (Exception e) {
System.out.print("错误。。。");
} finally {
lock.unlock();
}
}, "Thread A");
Thread threadB = new Thread(() -> {
try {
latchB.await();
} catch (Exception e) {
System.out.print("错误");
}
lock.lock();
try {
for (int i = 0; i < 10; i++) {
System.out.print("B");
// 叫醒b
cC.signal();
if (i == 0) {
latchC.countDown();
}
cB.await();
}
cC.signal();
} catch (Exception e) {
System.out.println("错误。。。");
} finally {
lock.unlock();
}
}, "Thread B");
Thread threadC = new Thread(() -> {
try {
latchC.await();
} catch (Exception e) {
System.out.print("错误");
}
lock.lock();
try {
for (int i = 0; i < 10; i++) {
System.out.print("C");
// 叫醒A
cA.signal();
cC.await();
}
cA.signal();
} catch (Exception e) {
System.out.print("错误。。。");
} finally {
lock.unlock();
}
}, "Thread B");
threadA.start();
threadB.start();
threadC.start();
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。