开发者

Java Threading Issue

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();
   开发者_如何学Go }
}

Now, my questions are:

  1. 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.
  2. Can I still notify other threads holding the interrupted thread's object? Like in the sample code.


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.


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.


  1. Yes: But you don't really need to have the lock before calling interrupt.
  2. Yes


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.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜