美文网首页
两个线程交替数字

两个线程交替数字

作者: overflow_e4e4 | 来源:发表于2020-05-12 20:48 被阅读0次
/**
 * 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();

    }
}

相关文章

网友评论

      本文标题:两个线程交替数字

      本文链接:https://www.haomeiwen.com/subject/vgiinhtx.html