兩個線程交替打印a b 0到25

public class CriclePrint {
    private static volatile boolean flag = true;

    private static volatile int value = 0;

    private static Object object = new Object();

    private static final char A = 'A';
    private static final int SLEEP = 1000;

    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            while (true) {
                if (flag){
                    try {
                        Thread.sleep(SLEEP);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (object) {
                        System.out.println((char) (A + value));
                        flag = false;
                        try {
                            object.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });

        Thread thread2 = new Thread(() -> {
            while (true) {
                if (!flag){
                    try {
                        Thread.sleep(SLEEP);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (object) {
                        System.out.println(value);
                        value++;
                        if (value == 26){
                            value = 0;
                        }
                        flag = true;
                        object.notify();
                    }
                }
            }
        });
        thread1.setName("輸出ASCII");
        thread2.setName("輸出NUMBER");
        thread1.start();
        thread2.start();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章