wait和notify实现两个线程打印奇偶数

今天想起前段时间的一道面试编程题,要求两个线程实现打印奇偶数,当时因为没能很好的理解wait和notify。所以代码有问题。今天又查了下,重新试了下,先上正确结果:

偶数线程

public static class Thread1 extends Thread {

        Object lock;
        public Thread1(Object lock) {
            this.lock = lock;
        }

        @Override
        public void run() {
            super.run();
            synchronized (lock) {

                while (true && i < 100) {
                    if (i % 2 == 0) {
                        System.out.println("--Thread1-->" + i);
                        i++;
                        lock.notify();
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
        }
    }

奇数线程

public static class Thread2 extends Thread {

        Object lock;

        public Thread2(Object lock) {
            this.lock = lock;
        }

        @Override
        public void run() {
            super.run();
            synchronized (lock) {
                while (true && i < 100) {
                    if (i % 2 == 1) {
                        System.out.println("--Thread2-->" + i);
                        i++;
                        lock.notify();
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }

                }
            }
        }
    }

主函数

public static void main(String[] args) {
        Object lock = new Object();
        Thread t1 = new Thread1(lock);
        Thread t2 = new Thread2(lock);
        t1.start();
        t2.start();
    }

可以简单理解成lock.notify()是唤醒别人,lock.wait()是休眠自己。

而且要注意放在synchronized代码块中,否则会报IllegalMonitorStateException异常。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容