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:
public class ParameterizedRunnable implements Runnable {
private final Object parameter;
public ParameterizedRunnable(Object parameter) {
this.parameter = parameter;
}
public void run() {
// Use the passed parameter here
}
}
You can then use this class to create a thread and pass the parameter to it:
Runnable runnable = new ParameterizedRunnable(myParameter);
new Thread(runnable).start();
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:
Thread thread = new Thread(() -> {
// Use the passed parameter here
}, myParameter);
thread.start();
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3