Home > Java > javaTutorial > How do I Pass Parameters to Java Threads?

How do I Pass Parameters to Java Threads?

Susan Sarandon
Release: 2024-11-05 15:30:02
Original
712 people have browsed it

How do I Pass Parameters to Java Threads?

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>
Copy after login
<code class="java">Runnable r = new MyRunnable(param_value);
new Thread(r).start();</code>
Copy after login

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

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!

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