交替打印ABC

developS / 2023-09-05 / 原文

package test11;

public class PrintABC {

    private static  int state = 0;

    private static  final Object lock  = new Object();

    public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    for (int i=0;i<100;i++){
                        synchronized (lock){
                            while (state%3 !=0){
                                lock.wait();
                            }
                            System.out.println("A");
                            state++;
                            lock.notifyAll();
                        }
                    }

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


        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    for (int i=0;i<100;i++){
                        synchronized (lock){
                            while (state%3 !=1){
                                lock.wait();
                            }
                            System.out.println("B");
                            state++;
                            lock.notifyAll();
                        }
                    }

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



        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    for (int i=0;i<100;i++){
                        synchronized (lock){
                            while (state%3 !=2){
                                lock.wait();
                            }
                            System.out.println("C");
                            state++;
                            lock.notifyAll();
                        }
                    }

                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        t2.start();
        t3.start();
    }


}