wait和notify實(shí)現(xiàn)兩個線程打印奇偶數(shù)

今天想起前段時(shí)間的一道面試編程題,要求兩個線程實(shí)現(xiàn)打印奇偶數(shù),當(dāng)時(shí)因?yàn)闆]能很好的理解wait和notify。所以代碼有問題。今天又查了下,重新試了下,先上正確結(jié)果:

偶數(shù)線程

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();
                        }

                    }
                }
            }
        }
    }

奇數(shù)線程

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();
                        }

                    }

                }
            }
        }
    }

主函數(shù)

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代碼塊中,否則會報(bào)IllegalMonitorStateException異常。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容