使用ReentrantLock重入锁实现线程之间的排序

Posted Zeran

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用ReentrantLock重入锁实现线程之间的排序相关的知识,希望对你有一定的参考价值。

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

}

以上是关于使用ReentrantLock重入锁实现线程之间的排序的主要内容,如果未能解决你的问题,请参考以下文章

Java并发程序设计(12)并发锁之可重入锁ReentrantLock

ReentrantLock 重入锁(下)

重入锁

ReentrantLock (重入锁) 源码浅析

经典笔试题:线程通信(使用重入锁(ReentrantLock)和条件队列(Condition)实现线程间通信)

java多线程---重入锁ReentrantLock