Why does Threads in BLOCKED state do not get interrupted?

拥有回忆 提交于 2019-12-02 00:57:00

One assumes that you mean cause the thread to stop its current operation and throw an InterruptedException? A thread interrupt in Java is just a flag. You can call interrupt() just fine on a BLOCKED thread and that flag will be seen next time code checks for it.

The principle problem with implementing such a functionality is, how is a keyword (synchronized) supposed to throw an exception? InterruptedException is a checked exception, it would not be a useful exercise to have to declare every synchronized method (and block) in the language with throws InterruptedException!

An interrupt is a communication tool, it's generally for letting a thread know about a system state it needs to check on. The name is a legacy carry over/upward from flags set within hardware to let microprocessors know about a particular state (such as new values set on some input pins) that needs to be examined. Do not read too much into the name "interrupt" and think it's meant to be a tool for breaking the flow of the program within another thread. It is not. Hence even the methods that do throw an exception declare it as checked, the other thread is free to ignore it and resume waiting if it wants. Being able to arbitrarily break another thread's BLOCKED state would break the program flow, which is not the purpose.

Blocked Threads can receive Interrupts. You may have to check Thread.currentThread().interrupted() to see whether Thread got interrupt when it was waiting to acquire any resource.

See Also Lock::lockInterruptibly()

A blocked thread can be interrupted. Here is how interrupt is called on a thread depending on which state it is. From javadocs:

The checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.

If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.

If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.

If this thread is blocked in a Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.

If none of the previous conditions hold then this thread's interrupt status will be set.

Interrupting a thread that is not alive need not have any effect.

Throws: SecurityException - if the current thread cannot modify this thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!