Home > Java > javaTutorial > body text

How to Pass Parameters to Java Threads?

Mary-Kate Olsen
Release: 2024-11-06 17:41:02
Original
269 people have browsed it

How to Pass Parameters to Java Threads?

Passing Parameters to Java Threads

In Java, threads are created by implementing the Runnable interface. By default, Runnable objects do not take any arguments. However, if you need to pass parameters to a thread, there are two strategies: wrapper classes or anonymous classes.

Wrapper Classes

One way to pass parameters to a thread is to use a wrapper class. This involves creating a class that implements the Runnable interface and accepts the desired parameters in its constructor. Here's an example:

<code class="java">public class ParameterizedRunnable implements Runnable {

    private final Object parameter;

    public ParameterizedRunnable(Object parameter) {
        this.parameter = parameter;
    }

    public void run() {
        // Use the passed parameter here
    }
}</code>
Copy after login

You can then use this class to create a thread and pass the parameter to it:

<code class="java">Runnable runnable = new ParameterizedRunnable(myParameter);
new Thread(runnable).start();</code>
Copy after login

Anonymous Classes

Anonymous classes can also be used to pass parameters to threads. An anonymous class is a class that is defined and instantiated at the same time. Here's an example of using an anonymous class to pass a parameter to a thread:

<code class="java">Thread thread = new Thread(() -> {
    // Use the passed parameter here
}, myParameter);
thread.start();</code>
Copy after login

In this example, the lambda expression passed to the Thread constructor defines an anonymous class that implements the Runnable interface and receives the myParameter as its parameter.

The above is the detailed content of How to 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!