Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does wait know about interrupt in Java?

Thread.interrupt interrupts such calls as sleep, join and wait. I wonder how it is exactly implemented.

I know Thread.interrupt sets a flag isInterrupted. Does wait just polls this flag ? I hope it does not. So my question is how wait "knows" about interrupt.

like image 544
Michael Avatar asked Apr 15 '13 07:04

Michael


People also ask

Can a waiting thread be interrupted?

A thread that is in the sleeping or waiting state can be interrupted with the help of the interrupt() method of Thread class.

How does wait work in Java?

The wait() Method Simply put, calling wait() forces the current thread to wait until some other thread invokes notify() or notifyAll() on the same object. For this, the current thread must own the object's monitor.

How do I know if a thread is interrupted?

isInterrupted() The interrupted() is a static method in Thread class that determines if the current thread has been interrupted. The isInterrupted() is an instance method that tests if this thread instance has been interrupted. "The interrupted status of the thread is cleared by this method".

Is wait () in thread class?

wait() method is a part of java. lang. Object class. When wait() method is called, the calling thread stops its execution until notify() or notifyAll() method is invoked by some other Thread.


1 Answers

wait() does not poll. interrupt() checks the state of the interrupted thread. If it runs, it just sets the flag. If it is in wait(), sleep(), or join(), the interrupting thread also queues it to processor. When interrupted thread resumes execution, it first checks the flag, and throws InterruptedException if the flag was on.

like image 188
Alexei Kaigorodov Avatar answered Oct 28 '22 18:10

Alexei Kaigorodov