两个线程交替数字

2020-05-12  本文已影响0人  overflow_e4e4
/**
 * AB线程交替打印数字
 */
public class PrintAsOrder {
    static int i = 0;

    static Object sync = new Object();

    static class ThreadA extends Thread {
        public ThreadA() {
            super("ThreadA");
        }

        @Override
        public void run() {
            while (i < 100) {
                synchronized (sync) {
                    System.out.println(i + Thread.currentThread().getName());
                    i++;
                    sync.notifyAll();
                    try {
                        sync.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }
    }

    static class ThreadB extends Thread {
        public ThreadB() {
            super("ThreadB");
        }

        @Override
        public void run() {
            while (i < 100) {
                synchronized (sync) {
                    if (i == 0) {
                        sync.notifyAll();
                        try {
                            sync.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(i + Thread.currentThread().getName());
                    i++;
                    sync.notifyAll();
                    try {
                        sync.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }


    public static void main(String[] args) {
        new ThreadB().start();
        new ThreadA().start();

    }
}

上一篇下一篇

猜你喜欢

热点阅读