Java进阶程序员首页投稿(暂停使用,暂停投稿)

Java多线程,循环打印“ABC”10次

2017-08-06  本文已影响535人  被称为L的男人

思路

3个线程A,B,C分别打印三个字母,每个线程循环10次,首先同步,如果不满足打印条件,则调用wait()函数一直等待;之后打印字母,更新state,调用notifyAll(),进入下一次循环。

代码

package test;

public class PrintABC {
    private static final int PRINT_A = 0;
    private static final int PRINT_B = 1;
    private static final int PRINT_C = 2;
    
    private static class MyThread extends Thread {
        int which; // 0:打印A;1:打印B;2:打印C
        static volatile int state; // 线程共有,判断所有的打印状态
        static final Object t = new Object();
        
        public MyThread(int which) {
            this.which = which;
        }
        
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                synchronized (t) {
                    while (state % 3 != which) {
                        try {
                            t.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print(toABC(which)); // 执行到这里,表明满足条件,打印
                    state++;
                    t.notifyAll(); // 调用notifyAll方法
                }
            }
        }
    }
    
    public static void main(String[] args) {
        new MyThread(PRINT_A).start();
        new MyThread(PRINT_B).start();
        new MyThread(PRINT_C).start();
    }

    private static char toABC(int which) {
        return (char) ('A' + which);
    }
}
上一篇下一篇

猜你喜欢

热点阅读