交替打印

使用 condition 交替打印字符串 A、B、C

 

public class PrintTest {

    private volatile static int num = 1;

    private static ReentrantLock lock = new ReentrantLock();

    private final static Condition conditionA = lock.newCondition();
    private final static Condition conditionB = lock.newCondition();
    private final static Condition conditionC = lock.newCondition();

    public static void main(String[] args) {

        Thread threadA = new Thread() {
            @Override
            public void run() {
                try {

                    lock.lock();
                    while (num != 1) {
                        conditionA.wait();
                    }
                    num = 2;
                    System.out.println("A");
                    conditionB.signalAll();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {

                    if (lock.isHeldByCurrentThread()) {
                        lock.unlock();
                    }
                }


            }
        };

        Thread threadB = new Thread() {
            @Override
            public void run() {
                try {

                    lock.lock();
                    while (num != 2) {
                        conditionA.wait();
                    }
                    num = 3;
                    System.out.println("B");
                    conditionC.signalAll();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {

                    if (lock.isHeldByCurrentThread()) {
                        lock.unlock();
                    }
                }


            }
        };

        Thread threadC = new Thread() {
            @Override
            public void run() {
                try {

                    lock.lock();
                    while (num != 3) {
                        conditionA.wait();
                    }
                    num = 1;
                    System.out.println("C");
                    conditionA.signalAll();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {

                    if (lock.isHeldByCurrentThread()) {
                        lock.unlock();
                    }
                }


            }
        };


        threadA.start();
        threadB.start();
        threadC.start();

    }


}

输出

A
B
C

Process finished with exit code 0

 

posted @ 2022-04-06 00:20  纵码万水千山  阅读(76)  评论(0编辑  收藏  举报