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();
    }

}

Zeran
32 声望4 粉丝

学而不思则罔,思而不学则殆。


引用和评论

0 条评论