Java Runnable Interface

Introduction

The Runnable interface in Java represents a task that can be executed by a thread. It defines a unit of work that can run concurrently.

Table of Contents

  1. What is the Runnable Interface?
  2. Implementing Runnable
  3. Examples of Using Runnable
  4. Conclusion

1. What is the Runnable Interface?

The Runnable interface is a functional interface with a single method, run(), which contains the code to be executed by a thread.

2. Implementing Runnable

To use Runnable, implement the interface and override the run() method.

3. Examples of Using Runnable

Example 1: Basic Implementation of Runnable

This example demonstrates creating and running a thread using the Runnable interface.

public class RunnableExample {
    public static void main(String[] args) {
        Runnable task = () -> System.out.println("Thread is running.");
        Thread thread = new Thread(task);
        thread.start();
    }
}

Output:

Thread is running.

Example 2: Running Multiple Threads

This example shows how to create and run multiple threads using the Runnable interface with lambda expressions.

public class MultipleThreadsExample {
    public static void main(String[] args) {
        Runnable task1 = () -> System.out.println("Thread 1 is running.");
        Runnable task2 = () -> System.out.println("Thread 2 is running.");

        Thread thread1 = new Thread(task1);
        Thread thread2 = new Thread(task2);

        thread1.start();
        thread2.start();
    }
}

Output:

Thread 2 is running.
Thread 1 is running.

4. Conclusion

The Runnable interface in Java is essential for concurrent programming, allowing tasks to be executed by threads. Using lambda expressions simplifies the implementation, making the code more readable and concise.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top