简体   繁体   中英

Why i am getting following output from this java program?

class MyThread extends Thread 
{
    MyThread() 
    {
        System.out.print(" MyThread");
    }
    public void run() 
    {
        System.out.print(" bar");
    }
    public void run(String s) 
    {
        System.out.println(" baz");
    }
}
public class TestThreads 
{
    public static void main (String [] args) 
    {
        Thread t = new MyThread() 
        {
            public void run() 
            {
                System.out.println(" foo");
            }
        };
        t.start();
    }
}

Hello, I am new in java and currently learning Multithreading, When I am running the above program then i am getting this particular output MyThread foo please explain why?

MyThread comes from the constructor

foo comes from the run method which gets called when start() is called .

Essentially the run() method (which prints baz ) is overridden in your main .

and the run(String s) is an overloaded method which has no significance here.

It is executing the MyThread constructor and then executing the run() method .

Thread t = new MyThread() , you are trying to create a MyThread object and hence it executes the constructor.

MyThread() 
{
    System.out.print(" MyThread");
}

Then you start the thread t.start(); , it executes the run() method which you have overridden in main(String[] args) :

public void run() 
{
     System.out.println(" foo");
}

You first create an instance of MyThread , which calls the constructor and prints " MyThread". Then, you call t.start(); which calls the run method.

Even though you defined a run method printing " bar", it is overriden by the one in the main method (that prints " foo").

Try the following:

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

And see what happens!

The reason is that first when create object is invoked constructor MyThread and print first part of string. When you start thread, execution continue with run method and print foo .

The first output inside the default constructor of MyThread , and it overrides a run() method:

Thread t = new MyThread() 
        {
            public void run() 
            {
                System.out.println(" foo");
            }
        };

Output:

Thread foo

Thread t = new MyThread() ;

Output:

MyThread bar

Note that first one you overrode the run() method and used your custom message inside it, but the second will override run() by default in MyThread class.

You are overriding the run method when you create Thread t . This new implementation prints " foo", which takes priority over the one you implemented in your class MyThread which still runs its own constructor that prints "MyThread".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM