This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
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

Problem in thread

 
Poornima Sharma
Ranch Hand
Posts: 114
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi friends I cannot determine why the output is such.


public class Test {
public static void main(String[] args)
{
new MyThread().start();
new MyThread(new MyRunnable()).start();
}

}
class MyThread extends Thread
{
MyThread(){}
MyThread(Runnable r){super(r);}
public void run()
{
System.out.println("Inside Thread");
}
}
class MyRunnable implements Runnable
{
public void run()
{
System.out.println("Inside runnable");
}
}


The output of the code is

Inside Thread
Inside Thread
 
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
Check This similar problem
 
Paul Somnath
Ranch Hand
Posts: 177
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
You never run the MyRunnable thread.
To start a thread which is coded using implementing the Runnable Interface, you need to pass the runnable object to the Thread class.
Now in your code, you never pass the object to Thread class but instead pass it to MyThread class which extends the Thread class.
Since both the calls call MyThread's run method, so Inside Thread is printed twice!

Try this code:



Can you observe the difference now?
 
chander shivdasani
Ranch Hand
Posts: 206
Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The way you start a thread depends on the way you have defined it. If you have extended Thread class, then starting it is very simple. Just Create an instance and call Start method on that instance.

When you implement Runnable interface, you need to do three things
1. Create an instance of Class that implements Runnable.
2. Create a Thread instance and pass it the instance that is created in Step 1

3. Call the start method on the Thread instance.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic