Passing Parameters to Java Threads
In multithreaded programming, often it's essential to pass parameters to threads, enabling them to perform specific tasks with relevant data. Here's how to achieve this in Java:
Passing Parameters to Runnable Objects
Implement the Runnable interface and pass the parameter in its constructor. The thread will then be created using an instance of this Runnable object:
<code class="java">public class MyRunnable implements Runnable { private Object parameter; public MyRunnable(Object parameter) { this.parameter = parameter; } public void run() { // Use the passed parameter here... } }</code>
<code class="java">Runnable r = new MyRunnable(param_value); new Thread(r).start();</code>
Using Anonymous Classes
Anonymous classes allow you to create a Runnable object directly without defining a named class. Pass the parameter to the anonymous class constructor within the thread creation:
<code class="java">new Thread(() -> { // Anonymous class implementation // Use the passed parameter here... }).start();</code>
The above is the detailed content of How do I Pass Parameters to Java Threads?. For more information, please follow other related articles on the PHP Chinese website!