Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overriding start() in Threads

 
Thomas Markl
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Overriding start() in Threads
When I override start method in a Thread created by „extends Thread
and a Thread created by „implements Runnable“ there is a different
reaction – WHY?

Result:
C:\>java BackgroundTest4a
In start()
 Thread is not started but start() method of Background object is invoked.

C:\>java BackgroundTest4
Thread-2
 Thread is started and not start() von Background is invoked!
 
Neil Laurance
Ranch Hand
Posts: 183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because Runnable only defines one method: run.
So the call:
Thread thread = new Thread(runnable);
thread.run();
Calls the default run() method in the Thread base class, which in turn calls the start() method of the Runnable instance runnable.
HTH :roll: :roll:
 
Thomas Markl
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just thought it over:
- "extends Thread" => bgr.start() is of type "Background" as bgr is background instance. According to Polymorphism: Whith overridden method the type of the object determines the invoked method: => bgr is of type "Background" hence "Background" start() method is invoked and not the "super.start" of Thread class!
- "implements Runnable" => new Thread(bgr).start() => Instance of Runnable => according to polymorphism => start() method of Runnable is invoked and Thread is startet.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic