How can I pass a parameter to a Java Thread?
To pass a parameter to a Java thread, you can use a Runnable
object and pass the parameter to its constructor. Here's an example of how you can do this:
class MyRunnable implements Runnable {
private String parameter;
public MyRunnable(String parameter) {
this.parameter = parameter;
}
@Override
public void run() {
// use the parameter here
}
}
Thread thread = new Thread(new MyRunnable("Hello World"));
thread.start();
Alternatively, you can use a Callable
object and pass the parameter to its call()
method. Here's an example of how you can do this:
class MyCallable implements Callable<Void> {
private String parameter;
public MyCallable(String parameter) {
this.parameter = parameter;
}
@Override
public Void call() throws Exception {
// use the parameter here
return null;
}
}
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Void> future = executor.submit(new MyCallable("Hello World"));
I hope this helps! Let me know if you have any questions.