• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Threads

 
ramesh maredu
Ranch Hand
Posts: 210
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Following code is taken from whizlabs, can someone explain why output is

Thread1.run()
Thread1.run()


 
Ankit Garg
Sheriff
Posts: 9509
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't know the exact reason, but judging by the output, it is because the Thread1 class overrides the run method of Thread class. What the run method of Thread class do is check if this thread was created using a runnable by checking if a private instance of Runnable in Thread class is null or not. If it is not null, then it would call the run method of that object otherwise it would do nothing.



But in this case, the run method of the overriding class Thread1 class is invoked, so it doesn't do this check and directly displays Thread1.run()

This is what I feel but I may be wrong as this is just a prediction...
 
Paul Somnath
Ranch Hand
Posts: 177
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here in the code, you are actually never invoking the run method inside Thread2.
When you implement the Runnable interface, the Thread class should be passed the Runnable target for the run() method to execute as a new thread.
So if you want to execute the run() method of Thread2,
you will have to code like this:



In the original code, you never pass the Runnable target in the Thread object..
Any other suggestions are welcome.
[ September 04, 2008: Message edited by: Somnath Paul ]
 
Paul Somnath
Ranch Hand
Posts: 177
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can find a detailed surgery of the case here.

 
vidhya suvarna
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As you know you can create a thread either by extends the THREAD class or by implementing the RUNNABLE interface.

So in the code:
new Thread1().start --> is invoking the call to the RUN() method of THREAD1 which is a common way to create a new thread. Simpler way is:
Thread1 t1=new Thread1();
t1.start();

Now,
new Thread1(new Thread2()).start();--> First calls the 2nd constructor of THREAD1 i.e
Thread1(Runnable runnable) {
super(runnable);}--> which inturns call the constructor of THREAD with RUNNABLE agrument.
Simpler way is:
Thread2 t2=new Thread2();
Thread1 t1=new Thread1(t2);
t1.start(); -->which also invokes the THREAD1's start as its THREAD1's instance

i hope i have cleared your doubt.
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic