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

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

}
阅读 724

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

19 声望
2 粉丝
0 条评论

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

19 声望
2 粉丝
文章目录
宣传栏