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

How do you pass parameters to Java threads?

Linda Hamilton
Release: 2024-11-05 22:55:02
Original
1033 people have browsed it

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>
Copy after login

You can then invoke the thread like this:

<code class="java">Runnable r = new MyRunnable(param_value);
new Thread(r).start();</code>
Copy after login

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>
Copy after login

The parameter can be passed as a capture variable:

<code class="java">Object param_value = ...;
new Thread(() -> {
    // Use param_value here
}).start();</code>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template