Runnable
Runnable is an interface with a single method, run(), used to define a task that can be executed by a thread. It's an alternative to extending the Thread class directly.
1. What is Runnable?
Runnable is an interface with a single method, run(), used to define a task that can be executed by a thread. It's an alternative to extending the Thread class directly.
2. Why is it used?
Since Java allows extending only one class, using Runnable instead of extending Thread leaves your class free to extend some other class as well, if needed, while still defining thread-based behaviour.
3. Real-Life Example
Think of writing down a task on a piece of paper (the Runnable) and handing it to any available worker (a Thread) to actually carry out. The task itself is separate from who performs it.
4. Syntax
javaclass MyTask implements Runnable { public void run() { // code to run } } Thread t = new Thread(new MyTask()); t.start();
5. Example Program
javaclass MyTask implements Runnable { public void run() { System.out.println("Task running via Runnable"); } } public class RunnableDemo { public static void main(String[] args) { Thread t = new Thread(new MyTask()); t.start(); } }
Output:
Task running via Runnable6. Key Points to Remember
Runnableonly defines the task; it must still be passed to aThreadobject to actually run.- Using
Runnableis generally preferred over extendingThread, since it keeps your design more flexible. Runnablecan also be implemented easily using a lambda expression, since it's a functional interface.