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

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


        
3条回答
  •  离开以前
    2021-01-04 20:35

    1. Wait method is used to suspend a current thread on an object. Wait method is not from thread class but from java.lang.Object

    2. Notify method is used to wake the thread waiting on the object. Notify method is not from thread class but from java.lang.Object.

    3. Interrupt method is used to to indicate the current thread that is should stop current job execution and can start other job. Interrupt method is from thread class.

    Let see the real life example:

    Consider Telephone as Object , Person as Thread. Suppose for instance A person is using Telephone and B person also wants to use the telephone but as A person i.e (Thread 1) is busy using it unless the work is done acquires a lock on telephone Object now B i.e(Thread 2) tries to use Telephone but as A has acquired lock on it B it goes into wait state until lock is released.

    • If Telephone object calls wait method it will restrict current thread which want to use Telephone and it will go into wait state.
    • If Telephone object calls notify it will signal the thread waiting on it to acquire lock and proceed with the intended work.
    • If Person A(Thread 1) is using Telephone object and is in some task but interrupt method is called then A will be signaled to stop with current task and may need to do some other task assigned.

提交回复
热议问题