Pass a Parameter to a Java Thread



The Java threads provide a mechanism for the concurrent execution making it easier to perform the tasks in parallel. Often, we may need to pass parameters to a thread to ensure it operates with the specific input data. This article offers several practical approaches to passing parameters to a Java thread.

Also read: How to create a Java Thread?

Passing a Parameter to a Java Thread

There can be multiple ways to pass a parameter to a Java thread; here are some of the ways you can use:

Using a Custom Runnable Implementation

The simplest way to pass parameters to a thread is by creating a custom class that implements the Runnable interface and defining the parameters as fields.

Example

class ParameterizedTask implements Runnable {
    private String message;

    public ParameterizedTask(String message) {
        this.message = message;
    }

    @Override
    public void run() {
        System.out.println("Message: " + message);
    }
}

public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(new ParameterizedTask("Hello, World!"));
        thread.start();
    }
}

In this example, the message parameter is passed to the thread via the constructor of the ParameterizedTask class.

The output of the above example will be:

Message: Hello, World!

Using a Lambda Expression (Java 8 and Above)

If you are using Java 8 or later, the lambda expressions provide a concise way to pass parameters to a Java thread.

Example

public class Main {
    public static void main(String[] args) {
        String message = "Hello, Lambda!";

        Thread thread = new Thread(() -> {
            System.out.println("Message: " + message);
        });

        thread.start();
    }
}

In this case, the lambda expression directly accesses the message variable avoiding the need for a separate class.

The output of the above example will be:

Message: Hello, Lambda!

Using a Method Reference (Java 8 and Above)

If the task logic can be encapsulated in a method, we can use a method reference to pass parameters to a thread.

Example

public class Main {
    public static void printMessage(String message) {
        System.out.println("Message: " + message);
    }

    public static void main(String[] args) {
        String message = "Hello, Method Reference!";

        Thread thread = new Thread(() -> printMessage(message));
        thread.start();
    }
}

This approach combines the use of a method with lambda expressions to simplify parameter passing.

The output of the above example will be:

Message: Hello, Method Reference!
Updated on: 2025-01-16T12:38:04+05:30

315 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements