Java Intermediate

0% completed

Previous
Next
Java Runnable Interface

The Runnable interface is a core component of Java's multithreading framework. It represents a task that can be executed by a thread and defines a single method, run(), which contains the code that should execute concurrently. Unlike extending the Thread class, implementing Runnable allows a class to define a task while still extending another class if needed. This approach promotes better separation of concerns and makes your code more flexible and reusable.

Image

Why Use Runnable Instead of Extending Thread?

  • Single Inheritance Limitation:
    • Problem: Extending the Thread class restricts you from extending any other class since Java supports single inheritance.
    • Solution: Implementing Runnable allows your class to extend another class while still enabling multithreading.
  • Separation of Concerns:
    • The task (code in run()) is separated from the thread control mechanism. This makes the code more modular and easier to maintain.
  • Flexibility:
    • Runnable objects can be passed to a Thread constructor, enabling you to use different thread implementations without changing your task code.

Syntax and How to Execute a New Thread Using Runnable

// Implementing the Runnable interface: public class MyTask implements Runnable { @Override public void run() { // Code to be executed in the new thread } } // Executing a new thread: Thread thread = new Thread(new MyTask()); thread.start();
  • Explanation:
    • A class (MyTask) implements Runnable and overrides the run() method with the desired task.
    • To execute the task, a new Thread object is created by passing an instance of MyTask to its constructor.
    • Calling start() on the thread initiates the new thread, which in turn invokes the run() method.

Examples

Example 1: Basic Runnable Implementation

In this example, we define a class Task that implements Runnable. The run() method prints a simple message multiple times with a short pause using Thread.sleep(). We then create a thread with this task and start it.

Java
Java

. . . .

Example Explanation:

  • Task Class:
    • Implements Runnable and overrides run() to print a count from 1 to 5.
    • Uses Thread.sleep(1000) to pause for 1 second between iterations.
  • Thread Creation:
    • A new Thread is created with an instance of Task.
    • Calling start() initiates the thread, causing the run() method to execute concurrently with the main thread.
  • Concurrent Execution:
    • The main thread prints a message while the new thread executes independently.

The Runnable interface is a flexible way to define tasks that can be executed by threads without being limited by Java's single inheritance restriction. By implementing Runnable, you separate the task's logic from thread management, allowing greater modularity and reuse.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next