Home >Java >javaTutorial >How do you pass parameters to Java threads?

How do you pass parameters to Java threads?

Linda Hamilton
Linda HamiltonOriginal
2024-11-05 22:55:021056browse

How do you pass parameters to Java threads?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn