How can I pass a parameter to a Java Thread? How can I pass a parameter to a Java Thread? multithreading multithreading

How can I pass a parameter to a Java Thread?


You need to pass the parameter in the constructor to the Runnable object:

public class MyRunnable implements Runnable {   public MyRunnable(Object parameter) {       // store parameter for later user   }   public void run() {   }}

and invoke it thus:

Runnable r = new MyRunnable(param_value);new Thread(r).start();


For Anonymous classes:

In response to question edits here is how it works for Anonymous classes

   final X parameter = ...; // the final is important   Thread t = new Thread(new Runnable() {       p = parameter;       public void run() {          ...       };   t.start();

Named classes:

You have a class that extends Thread (or implements Runnable) and a constructor with the parameters you'd like to pass. Then, when you create the new thread, you have to pass in the arguments, and then start the thread, something like this:

Thread t = new MyThread(args...);t.start();

Runnable is a much better solution than Thread BTW. So I'd prefer:

   public class MyRunnable implements Runnable {      private X parameter;      public MyRunnable(X parameter) {         this.parameter = parameter;      }      public void run() {      }   }   Thread t = new Thread(new MyRunnable(parameter));   t.start();

This answer is basically the same as this similar question: How to pass parameters to a Thread object


via constructor of a Runnable or Thread class

class MyThread extends Thread {    private String to;    public MyThread(String to) {        this.to = to;    }    @Override    public void run() {        System.out.println("hello " + to);    }}public static void main(String[] args) {    new MyThread("world!").start();}