Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt on Threads..

 
Vepa Sritej
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class MyThread
{
//
other declarations etc//
...
...

public void run()
{
super.start();
}

public static void main(String ...ar)
{

Thread t=new MyThread();
t.start();
}
}

Here i thought in the run method super.start() will invoked the Thread class's run method which does nothing ...but to my suprise i got an exception mentioning we cannot restart a thread.

But if im not wrong if i put something like this.start(), then certainly an exception would come but how come super.thread() is same as invoking the present thread again.

Pls help.im taking my 1.5 exam tommorow...
 
Henry Wong
author
Marshal
Pie
Posts: 20892
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Vepa Sritej:

Here i thought in the run method super.start() will invoked the Thread class's run method which does nothing ...but to my suprise i got an exception mentioning we cannot restart a thread.

But if im not wrong if i put something like this.start(), then certainly an exception would come but how come super.thread() is same as invoking the present thread again.

Pls help.im taking my 1.5 exam tommorow...


Since you never overriden the start() method, there is no real difference between this.start() and super.start(), they both call the thread object's start() method... but to answer your question...

In your main method, you created the thread object and call the start() method, which creates the thread which calls the run the method. In your run() method, you are trying to restart the same thread, which has already been started, hence the exception.

After all, if the thread wasn't already started, then how did the start() method of your run() method even got called??


BTW, I wasn't implying that it was a good idea to override the start() method, from my answer.

Good luck on your test tommorrow,
Henry
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, Vepa, for this interesting question, will go in my collection.

Good luck on the exam!





But you should not learn today, you'd better relax. Just saying:"What I still don't know, I'll learn on Tuesday, after I cleared the exam."



Bu.
[ September 10, 2006: Message edited by: Burkhard Hassel ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic