Condition秩序印刷ABCD

2439 ワード

プログラムを作成し、3つのスレッドを開き、この3つのスレッドのIDはそれぞれA、B、Cであり、各スレッドは自分のIDを画面に10回印刷し、出力結果はABCの順序で表示しなければならない.如:ABCABC....順番に押す.

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

/**
 * @author zjq
 * @date 2020/3/25 16:56
 *
 *     ADC
 */
public class pcC {
    public static void main(String[] args) {
        Data3 data3 = new Data3();
        new Thread(()->{
            for(int i=0;i<10;i++){
                data3.printA();
            }
        },"A").start();
        new Thread(()->{
            for(int i=0;i<10;i++){
                data3.printB();
            }
        },"B").start();
        new Thread(()->{
            for(int i=0;i<10;i++){
                data3.printC();
            }
        },"C").start();
    }
}
class Data3{//      Lock
    private Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();

    private int num = 1;//num=1 A;num = 2 B;num =3 C
    public void printA(){
        lock.lock();
        try {
            //  
            while(num!=1){
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName()+"=======A");
            //       
            num = 2;
            condition2.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }


    }
    public void printB(){
        lock.lock();
        try {
            //  ,  -》  -》  
            while(num!=2){
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName()+"=========B");
            num = 3;
            condition3.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void printC(){
        lock.lock();
        try {
            //  
            while (num!=3){
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName()+"========C");
            num = 1;
            condition1.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

}