top of page
Writer's picturecompnomics

Thread Creation with the Runnable Interface in Java


Java offers multiple ways to create threads. In this post, we'll explore using the Runnable interface, a powerful and flexible approach for defining the tasks threads execute.

Why Use the Runnable Interface?

The Runnable interface provides a clear separation between the "what" and "how" of thread execution. Let's break it down:

  • What: The Runnable interface defines a single method named run(). This method contains the code you want the thread to execute.

  • How: The Thread class manages the thread lifecycle (creation, starting, termination). You create a Runnable object and pass it to the Thread class constructor.

This separation offers several advantages:

  • Flexibility: You can create multiple threads that share the same functionality by implementing the Runnable interface in different classes.

  • Code Reusability: The Runnable code can be reused across different threads or even passed as arguments to other methods.

  • Inheritance: You can extend existing classes and implement Runnable to add thread behavior without sacrificing the original class functionality.

Creating a Thread with Runnable: A Code Example

Here's a code example demonstrating thread creation using the Runnable interface:

Java

public class MyRunnable implements Runnable {

  @Override
  public void run() {
    // Code to be executed by the thread
    for (int i = 0; i < 5; i++) {
      System.out.println("Thread: " + Thread.currentThread().getName() + ", Count: " + i);
      try {
        Thread.sleep(1000); // Simulate some work (1 second delay)
      } catch (InterruptedException e) {
        System.out.println("Thread interrupted!");
      }
    }
  }

  public static void main(String[] args) {
    // Create a Runnable object
    MyRunnable runnable = new MyRunnable();

    // Create a Thread object with the Runnable object
    Thread myThread = new Thread(runnable);

    // Thread name can be set optionally
    myThread.setName("My Runnable Thread");

    // Start the thread
    myThread.start();

    // Continue executing the main thread
    System.out.println("Main thread running...");
  }
}

Explanation:

  1. We define a class MyRunnable that implements the Runnable interface.

  2. The run() method overrides the run() method of Runnable. This is where the thread's work will be done.

  3. In the main method, we create a new MyRunnable object.

  4. We create a new Thread object, passing the MyRunnable object to its constructor. This tells the Thread what code to execute when it starts.

  5. We can optionally set a name for the thread using setName().

  6. We call start() on the thread object, initiating its execution.

  7. The main thread continues executing, printing "Main thread running...".

Running the Code

This code will produce output similar to the previous example:

Main thread running...
Thread: My Runnable Thread, Count: 0
Thread: My Runnable Thread, Count: 1
Thread: My Runnable Thread, Count: 2
Thread: My Runnable Thread, Count: 3
Thread: My Runnable Thread, Count: 4

The output demonstrates concurrent execution between the main thread and the thread created using the Runnable interface.

Conclusion

The Runnable interface provides a versatile approach to creating threads in Java. By separating the thread's task from its lifecycle management, you gain flexibility and code reusability. Leverage this technique to effectively structure your multithreaded applications.

11 views0 comments

Recent Posts

See All

Bình luận

Đã xếp hạng 0/5 sao.
Chưa có xếp hạng

Thêm điểm xếp hạng
bottom of page