Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass a parameter to a Java Thread?

Can anyone suggest to me how I can pass a parameter to a thread?

Also, how does it work for anonymous classes?

like image 471
Steve Avatar asked May 18 '09 10:05

Steve


1 Answers

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(); 
like image 177
Alnitak Avatar answered Sep 29 '22 15:09

Alnitak