简体   繁体   中英

Do we override run method when child class is extended from thread parent class

When we Subclass Thread, do we override its run method? We know Thread class itself implements Runnable, but there is no body for run method defined in Runnable class.

This is picture in my mind:

Runnable - Parent class-it has a run method in it, with empty body.

Thread- Child,

classA extends Thread- Child of Child,

when we define run() method in "classA" , are we overriding run method declared in Runnable class? Thank you for your time.

There are two ways to define the behavior of a thread: subclass the Thread class, or implement the Runnable interface.

For the first way, simply extend the Thread class and override the run() method with your own implementation:

public class HelloThread extends Thread {
    @Override
    public void run() {
        System.out.println("Hello from a thread!");
    }
}

public class Main { 
    // main method just starts the thread 
    public static void main(String args[]) {
        (new HelloThread()).start();
    }
}

However, the preferred way of implementing the logic for a Thread is by creating a class that implements the Runnable interface:

public class HelloRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("Hello from a thread!");
    }
}

public class Main {
    // notice that we create a new Thread and pass it our custom Runnable
    public static void main(String args[]) {
        (new Thread(new HelloRunnable())).start();
    }
}

The reason that implementing Runnable is preferred is that it provides a clear separation between the behavior of the thread and the thread itself. For instance, when using a thread-pool you never actually create the thread from scratch, you just pass a Runnable to the framework and it'll execute it on an available thread for you:

public class Main {
    public static void main(String args[]) {
        int poolSize = 5;
        ExecutorService pool = Executors.newFixedThreadPool(poolSize);
        pool.execute(new HelloRunnable());
    }
 }

Further Reading:

You should extend the Thread , only when are you going to rewrite the functionality of thread or improve its performance .

Interface tells you that , if you use this interface , you will get the funcationality.In your case , your buisness logic needs to be run in a thread then use interface.

If you a better way of running thread efficiently then extend the Thread.

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