Reputation: 1658
I'm synchronizing on the object of the thread like this:
synchronized(threadObject){
try{
threadObject.interrupt();
}catch(Exception ex){
//catch error here.
}finally{
threadObject.notifyAll();
}
}
Now, my questions are:
Upvotes: 2
Views: 119
Reputation: 719679
The answer to both questions is yes.
However, there is something a bit strange about your example. I've never come across a case where you would use a Thread
as a primitive lock. And it what you are doing in the example doesn't seem to achieve anything.
If threadObject
is the same as Thread.currentThread()
, then the call to interrupt()
will just set this thread's interrupted flag ... which be noticed in that code fragment.
if threadObject
is some other Thread
object then that thread will be interrupted. But we can't see (here) the code that that thread will be executing, and we don't know if it will be waiting on threadObject
. If not the interrupt()
and notify()
well got to different threads ...
The bottom line is that you wouldn't normally use a Thread object as a lock, and you wouldn't normally send use an interrupt() as an ersatz notify().
(Maybe this example is not intended to represent a real use-case.)
Upvotes: 0
Reputation: 421310
It is possible to interrupt a thread inside a synchronized block whose object that was synchronized was the thread to be interrupted? Like in the sample code.
Yes. I can't see why that wouldn't work. The synchronized
keyword is quite orthogonal to the interrupt
method. (Note that contrary to await
and notify
, you're not required to own the objects monitor when calling interrupt
.)
Can I still notify other threads holding the interrupted thread's object? Like in the sample code.
Yes, you can call notifyAll
on any object as long as you own the objects monitor. Again, the wait/notify
-mechanism is quite orthogonal to the interrupt
method.
Your question seem to indicate that you've misunderstood the use of synchronized
. The usual use-case is to synchronize on an object representing some resource which you like to avoid concurrent access to. The thread itself rarely represent such resource.
Upvotes: 1
Reputation: 24801
Upvotes: 0
Reputation: 82599
The object works as it normally does. The only stipulation is that other threads that synchronize on threadObject's monitor will block until you're complete with your thread. So yes, you can do both of those.
Upvotes: 0