Odd even number printing using thread

前端 未结 13 2020
挽巷
挽巷 2020-11-29 08:39

Odd even number printing using thread.Create one thread class, two instance of the thread. One will print the odd number and the other will print the even number.

13条回答
  •  借酒劲吻你
    2020-11-29 09:24

    You're waiting and notifying different objects (monitors).

    The idea is that you can call obj.wait() to wait for someone to do obj.notify(), while you're doing objA.wait() and objB.notify().

    Change your printOdd method to something like

    private void printOdd(int i) {
        synchronized (lock) {                        // <-------
            while (!oddTurn) {
                try {
                    lock.wait();                     // <-------
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(type + i);
            oddTurn = false;
            lock.notifyAll();                        // <-------
        }
    }
    

    and the printEven method similarly.

    Then provide the NumberPrinter with a lock object:

    Object lock = new Object();
    Thread odd = new Thread(new NumberPrinter("odd", lock));
    Thread even = new Thread(new NumberPrinter("even", lock));
    

    Output:

    odd1
    even2
    odd3
    even4
    odd5
    even6
    odd7
    even8
    odd9
    

提交回复
热议问题