Java
Runnable interface
multithreading
parameter passing
Java programming

Runnable with a parameter?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In Java, concurrency is an essential aspect for developing applications that perform multiple tasks simultaneously. One of the primary constructs used to achieve concurrency is the Runnable interface. However, a common challenge when working with the Runnable interface is passing parameters to the run method. This article explores how to implement Runnable with parameters, providing technical explanations and examples.

Understanding Runnable

The Runnable interface in Java is a functional interface that requires the implementation of a single method, run(). The Runnable interface is designed to be used as the target for threads. The basic syntax is as follows:

java
1@FunctionalInterface
2public interface Runnable {
3    void run();
4}

Here, the run method does not accept any parameters, which can be limiting when specific data needs to be passed into a thread. Therefore, strategies need to be employed to work around this limitation.

Strategies for Passing Parameters in Runnable

1. Using Constructor Parameters

One of the most common solutions to pass parameters to a Runnable is by using constructor parameters. By defining a custom class that implements Runnable, the constructor can accept parameters that are stored in instance variables. These variables can then be used within the run method.

java
1public class ParameterizedRunnable implements Runnable {
2    private final String threadName;
3    private final int count;
4
5    public ParameterizedRunnable(String threadName, int count) {
6        this.threadName = threadName;
7        this.count = count;
8    }
9
10    @Override
11    public void run() {
12        for (int i = 0; i < count; i++) {
13            System.out.println(threadName + ": " + i);
14        }
15    }
16}
17
18public class Main {
19    public static void main(String[] args) {
20        Thread thread = new Thread(new ParameterizedRunnable("Thread-1", 10));
21        thread.start();
22    }
23}

2. Using Lambda Expressions

With the introduction of lambda expressions in Java 8, creating concise implementations of Runnable became straightforward. However, directly passing parameters through lambda expressions into Runnable still requires either final or effectively final variables. Here is an example demonstrating this:

java
1public class Main {
2    public static void main(String[] args) {
3        final String message = "Hello from ";
4        Thread thread = new Thread(() -> {
5            System.out.println(message + Thread.currentThread().getName());
6        });
7        thread.start();
8    }
9}

3. Using Inner Classes

Another way to pass parameters is through inner classes. Although less modern than lambdas, inner classes provide a clear structure and maintain the link to outer variables.

java
1public class Main {
2    public static void main(String[] args) {
3        String threadName = "InnerClassThread";
4        int repeat = 5;
5
6        Runnable runnable = new Runnable() {
7            @Override
8            public void run() {
9                for (int i = 0; i < repeat; i++) {
10                    System.out.println(threadName + ": " + i);
11                }
12            }
13        };
14
15        Thread thread = new Thread(runnable);
16        thread.start();
17    }
18}

Comparison Table

Below is a table summarizing the key differences and use-cases for each method of passing parameters to a Runnable:

StrategyApproachUse-Case
Constructor ParametersCreate a class with fields and pass data through the constructor.When specific data needs to be set during object construction.
Lambda ExpressionsUse lambda expressions with effectively final variables.Ideal for simple tasks where code clarity and conciseness are prioritized.
Inner ClassesUtilize inner or anonymous classes with accessible variables.Useful in older Java versions or when maintaining legacy code.

Conclusion

Working with Runnable in Java to pass parameters involves understanding how to work within the constraints of the run method. By leveraging constructor parameters, lambda expressions, or inner classes, developers can effectively pass and utilize parameters in concurrent tasks. Understanding these strategies not only enhances the ability to work with Java threads but also reinforces best practices in managing concurrency.

These solutions provide flexibility and clarity, making them essential tools in any Java developer's toolkit for managing concurrent processes effectively.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.