Java,三条线程依次交替输出十次ABC

public class MyThreadTest {
    public static void main(String[] args) {
        PrintABC printABC = new PrintABC();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    printABC.printA();
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    printABC.printB();
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    printABC.printC();
                }
            }
        }).start();
    }//main
}

class PrintABC {
    private int flag = 1;

    public synchronized void printA() {
        while (flag != 1) {
            try {
                this.wait();// this表示当前方法所在的对象
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        flag = 2;
        System.out.println("A"+ "," + Thread.currentThread().getName());
        this.notifyAll();
    }

    public synchronized void printB() {
        while (flag != 2) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        flag = 3;
        System.out.println("B"+ "," + Thread.currentThread().getName());
        this.notifyAll();
    }

    public synchronized void printC() {
        while (flag != 3) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        flag = 1;
        System.out.println("C"+ "," + Thread.currentThread().getName());
        this.notifyAll();
    }
}
A,Thread-0 B,Thread-1 C,Thread-2 A,Thread-0 B,Thread-1 C,Thread-2 A,Thread-0 B,Thread-1 C,Thread-2 A,Thread-0 B,Thread-1 C,Thread-2 A,Thread-0 B,Thread-1 C,Thread-2 A,Thread-0 B,Thread-1 C,Thread-2 A,Thread-0 B,Thread-1 C,Thread-2 A,Thread-0 B,Thread-1 C,Thread-2 A,Thread-0 B,Thread-1 C,Thread-2 A,Thread-0 B,Thread-1 C,Thread-2
相关文章

相关标签/搜索