其他分享
首页 > 其他分享> > 交替打印

交替打印

作者:互联网

使用 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

 

标签:Thread,lock,打印,private,交替,num,static,conditionA
来源: https://www.cnblogs.com/guanbin-529/p/16104672.html