Skip to content
C

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

java
class MyTask implements Runnable { public void run() { // code to run } } Thread t = new Thread(new MyTask()); t.start();

5. Example Program

java
class 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 Runnable

6. Key Points to Remember

  • Runnable only defines the task; it must still be passed to a Thread object to actually run.
  • Using Runnable is generally preferred over extending Thread, since it keeps your design more flexible.
  • Runnable can also be implemented easily using a lambda expression, since it's a functional interface.