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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With