UltimatePraveeeee
UltimatePraveeeee

Reputation: 155

In Java why Thread class is created as Concrete Class?

We know that there are two ways to create a Thread in Java.

  1. Implementing Runnable Interface
  2. Extending the Thread Class [Thread is a Concrete Class with default implementation for run() method]

In the second approach, we have to provide the implementation for run() method to have our thread logic, executed. If so, then why JDK developers have not made run() method as abstract in Thread Class?

I am interested in knowing the reason behind, providing the default implementation for run() method in Thread Class.

Upvotes: 0

Views: 686

Answers (3)

Aniket Thakur
Aniket Thakur

Reputation: 68975

You cannot have abstract methods in non abstract class!

So having a abstract method in Thread would have to make Thread class abstract as well. Then why stop there? Make it an interface. But wait.. we already have Runnable interface that Thread class implements.

Also note we call start() method and not the run() method. start() will start a new Thread of execution. run() will just run the method in current Thread.

Also run() method is overridden. The method comes from Runnable interface.

public
interface Runnable {
    public abstract void run();
}

Extending Thread is just an alternate way for Thread creation and it cannot be abstract as you will not be able to create Thread Objects without writing a concrete implementation yourself.

Upvotes: 0

Chris K
Chris K

Reputation: 11925

You have almost answered your own question. Here is the default implementation of run

public void run() {
    if (target != null) {
        target.run();
    }
}

That is, the default implementation invokes the Runnable that was passed in via the constructor. Which is the first approach that you mentioned in your question.

new Thread( runnable ).start();

If run had instead been declared as abstract, then as kajacx has also pointed out; then that approach would not have compiled.

Upvotes: 3

kajacx
kajacx

Reputation: 12939

If Thread#run() was abstract, then following would be a compile error:

Thread t = new Thread(myRunnable);

Upvotes: 7

Related Questions