JAVA循环打印ABC的多种方式

1.Condition

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

/**
 * 三个线程循环打印ABC
 *
 * @author gaokuo
 * @since 2020-03-11 13:59
 **/
public class PrintABC {

    private final static Lock LOCK = new ReentrantLock();

    private static int count = 10;

    private static Condition condition = LOCK.newCondition();

    private static String afterPrint = "A";

    @SuppressWarnings("all")
    public static void main(String[] args) {
        count = 1;
        new Thread(()->PrintABC.deal("A")).start();
        new Thread(()->PrintABC.deal("B")).start();
        new Thread(()->PrintABC.deal("C")).start();
    }

    /**
     * catch异常
     */
    private static void deal(String str){
        try {
            print(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void print(String str) throws Exception {
        for(int i = 0; i< count;i++){
            while(true){
                if(sort(str)){
                    break;
                }
            }
            System.out.println(str);
            LOCK.lock();
            condition.signalAll();
            LOCK.unlock();
        }
    }

    /**
     * 顺序控制器
     */
    private static boolean sort(String str) throws Exception {
        if(Objects.equals(afterPrint, str)){
            if(Objects.equals("A",afterPrint)){
                afterPrint = "B";
            }else if(Objects.equals("B",afterPrint)){
                afterPrint = "C";
            }else if(Objects.equals("C",afterPrint)){
                afterPrint = "A";
            }else {
                throw new Exception("吗雷劈");
            }
            return true;
        }else{
            LOCK.lock();
            condition.await();
            LOCK.unlock();
            return false;
        }
    }

}

方式很多种,有时间就写.

你可能感兴趣的:(java)