Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an argument to a thread [duplicate]

Assume I would like to pass the following variable

String foo = "hello world";

as an argument to the following thread

new Thread(new Runnable() {

    @Override
    public void run() {
        // SOME CODE HERE REQUIRES VARIABLE
    }
}).start();

Can someone please explain how to do this.

Thanks.

like image 758
androideka Avatar asked Dec 27 '22 06:12

androideka


1 Answers

Subclass Thread:

public class MyThread extends Thread {

   private String arg;

   public MyThread(String arg) {
      this.arg = arg;
   }

   @Override
   public void run() {
        // Use your variable
   }
}
like image 200
Peter Bratton Avatar answered Jan 05 '23 17:01

Peter Bratton