Chowdappa
Chowdappa

Reputation: 1620

Run method in MyRunnable not calling

Why MyThread's run method calls If I pass MyRunnable to create a thread. But If I use Thread class my results are different. below is the code which makes confuse me. Please give any inputs.

public class ThreadDemo {

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

}

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

Upvotes: 0

Views: 345

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1504162

Your MyThread.run() method is overriding Thread.run() - and it's the Thread.run() implementation which calls the run method on the Runnable passed into the constructor. As documented:

If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.

If you change your MyThread.run() method to:

@Override
public void run() 
{ 
    System.out.print(" Inside Thread ");
    super.run();
} 

... it will print "Inside Thread" then "Inside Runnable" for the final call, i.e. if you trim your main method to just

new MyThread(new MyRunnable()).start(); 

the result will be

  Inside Thread
  Inside Runnable

Upvotes: 4

Related Questions