Passing Parameters to Java Threads
To pass parameters to a thread, you can use the constructor of the Runnable object to store the parameter for later use. The following code snippet demonstrates this:
<code class="java">public class MyRunnable implements Runnable { public MyRunnable(Object parameter) { // store parameter for later user } public void run() { } }</code>
To invoke the thread with a specific parameter, you can use the following syntax:
<code class="java">Runnable r = new MyRunnable(param_value); new Thread(r).start();</code>
Anonymous Classes
Anonymous classes can also be used to pass parameters to threads. The following code snippet shows how:
<code class="java">new Thread(new Runnable() { @Override public void run() { // code to be executed } }).start();</code>
In this example, an anonymous class is created that implements the Runnable interface. The parameter can be passed to the thread in the constructor of the anonymous class.
The above is the detailed content of How can parameters be passed to Java threads?. For more information, please follow other related articles on the PHP Chinese website!