1

What is happening in the background if I do this:

class TestThread {
     public static void main(String[] args) {
         Thread t = new Thread();
         t.start();

         System.out.println(t.getName());
     }
}

I know that to create a new thread you must override the run() method by either extending the Thread class or by implementing the Runnable interface.

If we implement the Runnable interface we have to provide the target run method where the code which has to run concurrently is provided.

Also, If we do not override the run() method and do not extend the Thread or implement the Runnable, the main() thread will execute.

I would like to know as to what exactly will happen in the background when I execute the above code? Does the main have a run() method like other Threads? Will this create a new Thread in addition to the main thread?

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142

2 Answers2

0

The new thread is created, starts, executes an empty* method, and terminates.

*) not really empty:

public void run() {
    if (target != null) {
        target.run();
    }
}
Barend
  • 17,296
  • 2
  • 61
  • 80
0
/**
 * 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.
 * 
 * Subclasses of Thread should override this method.
 */
public void run() {
    if (target != null) {
        target.run();
    }
}

Since you haven't set a Runnable target, nothing will happen.

Does the main have a run() method like other Threads?

Low-level API can be used for this purpose. They don't necessarily need to create a Thread instance to run a thread. Here is a good discussion: How main thread created by Java?

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142