Home  >  Article  >  Java  >  How to Pass Parameters to Java Threads?

How to Pass Parameters to Java Threads?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-06 17:41:02256browse

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>

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>

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>

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!

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