Passing Parameters to Java Threads
In Java, threads can be created by implementing the Runnable interface or by extending the Thread class. Both approaches provide methods for passing parameters to the thread.
Passing Parameters to Regular Threads
To pass a parameter to a regular thread using the Runnable interface, you need to store the parameter in the constructor of the Runnable object and access it within the run() method.
Example:
<code class="java">public class MyRunnable implements Runnable { private Object parameter; public MyRunnable(Object parameter) { this.parameter = parameter; } public void run() { // Use the parameter here } }</code>
You can then invoke the thread like this:
<code class="java">Runnable r = new MyRunnable(param_value); new Thread(r).start();</code>
Passing Parameters to Anonymous Threads
Anonymous threads are defined and started in a single statement. To pass a parameter to an anonymous thread, you can use a lambda expression:
<code class="java">new Thread(() -> { // Use the parameter here }).start();</code>
The parameter can be passed as a capture variable:
<code class="java">Object param_value = ...; new Thread(() -> { // Use param_value here }).start();</code>
The above is the detailed content of How do you pass parameters to Java threads?. For more information, please follow other related articles on the PHP Chinese website!