三个线程顺序打印ABC多次

三个线程顺序打印ABC五次:

package com.jintao.example.lock.orderprintstr;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author jinjueYang
 * @description 顺序打印五次ABC
 * @date 2019/11/18 9:02
 */
public class OrderPrintStr {

    public static void main(String[] args) throws InterruptedException {
        ReentrantLock reentrantLock = new ReentrantLock();
        Condition conditionA = reentrantLock.newCondition();
        Condition conditionB = reentrantLock.newCondition();
        Condition conditionC = reentrantLock.newCondition();
        new Thread(new PrintTask(reentrantLock, conditionA, conditionB, "A")).start();
        Thread.sleep(100);
        new Thread(new PrintTask(reentrantLock, conditionB, conditionC, "B")).start();
        Thread.sleep(100);
        new Thread(new PrintTask(reentrantLock, conditionC, conditionA, "C")).start();
    }

    static class PrintTask implements Runnable {
        //打印次数
        private static final int PRINT_COUNT = 5;
        private ReentrantLock reentrantLock;
        private Condition condition;
        private Condition nextCondition;
        private String printStr;

        public PrintTask(ReentrantLock reentrantLock, Condition condition, Condition nextCondition, String printStr) {
            this.reentrantLock = reentrantLock;
            this.condition = condition;
            this.nextCondition = nextCondition;
            this.printStr = printStr;
        } 

        @Override
        public void run() {
            reentrantLock.lock();
            try {
                for (int i = 0; i < PRINT_COUNT; i++) {
                    System.out.print(printStr);
                    //唤醒下一个线程打印
                    this.nextCondition.signal();
                    if (i < PRINT_COUNT - 1) {
                        //最后一次打印,无需等待,不然后续没有唤醒会死锁在这里
                        try {
                            this.condition.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } finally {
                reentrantLock.unlock();
            }
        }
    }
}

运行结果:

ABCABCABCABCABC

你可能感兴趣的:(算法)