File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Problem in thread Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Problem in thread" Watch "Problem in thread" New topic

Problem in thread

Poornima Sharma
Ranch Hand

Joined: Sep 09, 2008
Posts: 114
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(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

Poornima Sharma
SCJP 6.0
Ankit Garg

Joined: Aug 03, 2008
Posts: 9465

Check This similar problem

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Paul Somnath
Ranch Hand

Joined: May 19, 2008
Posts: 177
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?

Preparing for SCJP 6.0
chander shivdasani
Ranch Hand

Joined: Oct 09, 2007
Posts: 206

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.

Enjoy, Chander
SCJP 5, Oracle Certified PL/SQL Developer
I agree. Here's the link:
subject: Problem in thread
It's not a secret anymore!