Java:线程交替打印AB

115 阅读1分钟
public class ABTest {

    public static void main(String[] args) {
        Thread t1 = new Thread(new PrintA());
        Thread t2 = new Thread(new PrintB());
        t1.start();
        t2.start();
    }
    private static boolean flag = false;

    private static Object lock = new Object();

    private static class PrintA implements Runnable{
        @Override
        public void run() {
            while (true) {
                synchronized (lock) {
                    while (flag) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.println("A");
                    flag = true;
                    lock.notify();
                }
            }
        }
    }
    private static class PrintB implements Runnable{
        @Override
        public void run() {
            while (true) {
                synchronized (lock) {
                    while (!flag) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.println("B");
                    flag = false;
                    lock.notify();
                }
            }
        }
    }
}