Thread interrupt: will it cancel oncoming wait() call?

前端 未结 2 788
清酒与你
清酒与你 2021-02-04 09:11

I have a thread which has an incoming job queue (a LinkedList containing job descriptions). The thread blocks with wait() on the queue when there\'s no

2条回答
  •  無奈伤痛
    2021-02-04 10:00

    yes, your interrupted thread will throw an InterruptedException upon calling wait(). this is pretty simple to test for yourself.

    public class TestInt {
        public static void main(String[] args) throws Exception
        {
            Thread.currentThread().interrupt();
    
            synchronized(TestInt.class) {
                TestInt.class.wait();
            }    
        }    
    }
    

    also, note the javaodc for 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.

提交回复
热议问题