Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameter to Java Thread

Thread t = new Thread(new Runnable() { public void run() {} });

I'd like to create a thread this way. How can I pass parameters to the run method if possible at all?

Edit: To make my problem specific, consider the following code segment:

for (int i=0; i< threads.length; i++) {
    threads[i] = new Thread(new Runnable() {public void run() {//Can I use the value of i in the method?}});
}

Based on Jon's answer it won't work, since i is not declared as final.

like image 741
Terry Li Avatar asked Dec 17 '12 08:12

Terry Li


2 Answers

No, the run method never has any parameters. You'll need to put the initial state into the Runnable. If you're using an anonymous inner class, you can do that via a final local variable:

final int foo = 10; // Or whatever

Thread t = new Thread(new Runnable() {
    public void run() {
        System.out.println(foo); // Prints 10
    }
});

If you're writing a named class, add a field to the class and populate it in the constructor.

Alternatively, you may find the classes in java.util.concurrent help you more (ExecutorService etc) - it depends on what you're trying to do.

EDIT: To put the above into your context, you just need a final variable within the loop:

for (int i=0; i< threads.length; i++) {
    final int foo = i;
    threads[i] = new Thread(new Runnable() {
         public void run() {
             // Use foo here
         }
    });
}
like image 160
Jon Skeet Avatar answered Oct 14 '22 03:10

Jon Skeet


You may create a custom thread object that accepts your parameter, for example :

public class IndexedThread implements Runnable {
    private final int index;

    public IndexedThread(int index) {
        this.index = index;
    }

    public void run() {
        // ...
    }
}

Which could be used like this :

IndexedThread threads[] = new IndexedThread[N];

for (int i=0; i<threads.length; i++) {
    threads[i] = new IndexedThread(i);
}
like image 4
Frederik.L Avatar answered Oct 14 '22 02:10

Frederik.L