Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Should we call super.run()...

 
Jimmy Thomas
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it a good practice to call super.run() when we override the run() method of a Thread sub-class. The behaviour that I've noticed is that if we create a new subclassed Thread object using a Runnable object, then the run method will also get invoked for the Runnable object along with the Thread's run method sequentially.

This is how the code in java.lang.Thread class works, it calls the target's, i.e. the Runnable's run method.



The below code exhibits this scenario..


Output:
----------------------------------------------
Creating & starting new Thread
Creating & starting new Thread, with MyRun
MyRun.run()... Sleeping
Woke up
Creating & starting new MyThread
MyThread.run()
123
Creating & starting new MyThread, with MyRun
MyRun.run()... Sleeping
Woke up
MyThread.run()
123
----------------------------------------------
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you are creating a threadful monster here

When using threads we have the choice of two simple possibilities:
1. Extend the class Thread and override the run method (not calling super.run()). Then start an instance of the new thread class with start() method.

2. Implement interface Runnable. Pass an instance of the implemented Runnable to the constructor of a Thread object. Then start the new Thread object with the start() method.

That's it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic