Reputation: 21
I have a class that extends thread and in whose run() another method is called. I want that method to be synchronized, is it possible for a method that is defined in a thread subclass to be synchronized?
Upvotes: 1
Views: 246
Reputation: 27115
Short answer: There's nothing special about the Thread
class, and there's nothing special about any class that you define that extends Thread
. Sure, the Thread
class has methods that do things that other class methods don't do, but the same could be said of the String
class or the HashMap
class or any class that's worth writing.
Sure, Thread
is part of the Java standard library, and your class isn't. Sure, Thread
belongs to the java.lang
package, which actually is a little bit more special than other packages. But, even despite all of that...
...It's just a class.
P.S., Other answers here all contain good advice. Read 'em!
Upvotes: 0
Reputation: 140328
synchronized
is not part of the method signature. It is simply a shorthand for wrapping the method body in a block synchronized on either this
or TheEnclosingClass.class
.
This has a couple of consequences for methods in subclasses:
Upvotes: 2
Reputation: 2245
There is no problem with that. The reason is that every method is called within a thread anyhow. So in a thread's method call stack, somewhere a synchronized method or block may get executed. So, this method of yours is no different from any other that may be called in the stack.
Upvotes: 1