Could you explain what java.lang.Thread.interrupt() does when invoked?
Could you explain what java.lang.Thread.interrupt() does when invoked?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Thread.interrupt()sets the interrupted status/flag of the target thread. Then code running in that target thread MAY poll the interrupted status and handle it appropriately. Some methods that block such asObject.wait()may consume the interrupted status immediately and throw an appropriate exception (usuallyInterruptedException)Interruption in Java is not pre-emptive. Put another way both threads have to cooperate in order to process the interrupt properly. If the target thread does not poll the interrupted status the interrupt is effectively ignored.
Polling occurs via the
Thread.interrupted()method which returns the current thread’s interrupted status AND clears that interrupt flag. Usually the thread might then do something such as throw InterruptedException.EDIT (from Thilo comments): Some API methods have built in interrupt handling. Of the top of my head this includes.
Object.wait(),Thread.sleep(), andThread.join()java.util.concurrentstructuresInterruptedException, instead usingClosedByInterruptException.EDIT (from @thomas-pornin‘s answer to exactly same question for completeness)
Thread interruption is a gentle way to nudge a thread. It is used to give threads a chance to exit cleanly, as opposed to
Thread.stop()that is more like shooting the thread with an assault rifle.