What is the difference between wait/notify and wait/interrupt?

后端 未结 3 1691
攒了一身酷
攒了一身酷 2021-01-04 19:43
synchronized (Foo.class) {
    while (someCondition) {
        try {
            Foo.class.wait();
        } catch (InterruptedException e) {
            e.printStac         


        
3条回答
  •  礼貌的吻别
    2021-01-04 20:21

    Basically, you are not looking for a text book difference but difference in their uses cases.

    As folks have already pointed out, waking up the thread is not the only consequence but calling t1.interrupt() from Thread t2 for t1 will cause an InterruptedException in thread t1 and that is a big difference between Object.notify() and Thread.interrupt().

    You should understand that its method Object.wait() which throws checked InterruptedException and forces you to handle it. Object.wait.

    InterruptedException - if any thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.

    Then you should consult this question to get an idea about handling this exception.

    Difference between the two lies in the fact that one is for inter thread communication for usual logical programing stuff ( wait & notify ) and other one ( interrupt) is for preemptive thread cancellation / termination even in cases of blocking operations. You have to note that Java doesn't provide any mechanism to preemptively cancel a thread so you have to use interrupt mechanism for that purpose ( Obviously, if that is needed in your case. You might very well ignore this Exception if not applicable in your case).

    Java doesn't restrict your actions after InterruptedException and you can do anything you want but using it for things other than implementing Thread Cancellation Policy is not advised. Thread Cancellation Policy is often ignored and less discussed area when programmers write multi threaded programs and that is why you might be finding it difficult to understand the use case.

    What does an API method like BlockingQueue.put(..) is trying to tell you by throwing InterruptedException is that even its blocking operation can be preemptively terminated. Its not necessary that all blocking API methods will provide you that facility.

    Cancellation/Termination of a thread using Thread.interrupt() is not a forceful but cooperative mechanism and is just a request not an order.

    Your use of e.printStackTrace(); is strongly discouraged since this is usually not an error, if intention is to log it as an error.

    Hope it helps !!

提交回复
热议问题