
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Using a Lambda Expression (Java 8 and Above)
- Using a Method Reference (Java 8 and Above)
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!