Lux
Lux

Reputation: 21

Synchronized method in thread subclass

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

Answers (3)

Solomon Slow
Solomon Slow

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

Andy Turner
Andy Turner

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:

  • You can make an overriding method synchronized, even if the overridden method isn't.
  • If you don't make the overriding method synchronized, it doesn't "inherit" the synchronized-ness from the overridden method. You have to do it explicitly if you want it to be synchronized too.

Upvotes: 2

Sree Kumar
Sree Kumar

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

Related Questions