Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 254
ranjanarr Avatar asked Jan 21 '23 02:01

ranjanarr


1 Answers

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:

  • Thread Basics: http://download.oracle.com/javase/tutorial/essential/concurrency/runthread.html
  • Executors: http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ExecutorService.html
  • Interface basics: http://download.oracle.com/javase/tutorial/java/concepts/interface.html
like image 106
shj Avatar answered Feb 16 '23 00:02

shj