0

I know that when we call run() explicitly no new thread is started and the code written inside run() is executed on the main thread. But what if I give a name to a thread and then call run() explicitly as shown in my code?

public class ThreadImpl1 extends Thread{

    ThreadImpl1(String name){
        super(name);
        //start();
    }

    public void run() {
       for(int i=0;i<5;i++)
           System.out.println(getName());
   }

   public static void main(String...s) {
      ThreadImpl1 t1=new ThreadImpl1("thread1");
      t1.run();
      for(int i=0;i<5;i++)
           System.out.println(Thread.currentThread().getName());
   }
}

It gives the following output:

thread1
thread1
thread1
thread1
thread1
main
main
main
main
main

Why does the output show its name i.e. thread1? I haven't started the thread yet so it should print "main" all the time.

Cecilya
  • 519
  • 1
  • 5
  • 20
  • Why should it output _main_? You gave the `Thread` object a name of _thread1_. – GriffeyDog Jun 05 '18 at 16:12
  • I was expecting main 10 times in output because no new thread was created when I called t1.run() but I forgot that the call to getname() in the run() was implicitly converted to t1.getname() where t1 is the object of ThreadImpl1 class. That's what I was not able to figure out. – Abhishek Tomar Jun 05 '18 at 17:12

3 Answers3

3

It is because you are calling getName() in the run() method. This will return the value of the field "name" that you set.

You should call Thread.currentThread().getName().

Roger
  • 349
  • 3
  • 7
  • Yes, when I use Thread.currentThread().getName() instead of getName() in the run(), I get "main" all the time in output. Thank you. Now I get what I was missing. – Abhishek Tomar Jun 05 '18 at 17:08
1

The run method will be executed in the current thread just as normal method. No new thread will be created. And, try it to get the definitive answer :)

xingbin
  • 27,410
  • 9
  • 53
  • 103
0

When you call t1.run(); you do not start the thread but you just call the run() method of class ThreadImpl1 like a regular method.

Just like you call toString()... on a class

Mạnh Quyết Nguyễn
  • 17,677
  • 1
  • 23
  • 51