Passing parameter to Java Thread
Asked Answered
B

2

7
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.

Blest answered 17/12, 2012 at 8:16 Comment(4)
if it is possible it would be easier if you write a new class that implements Runnable and to pass to it all the parameters you need, in the constructor maybe.Balcke
In IntelliJ it has an auto-correct for this. It assigns variables used in anonymous classes to final variables for you.Scoville
I would suggest you to use THRAEDLOCAL , its a better way to keep and pass variables to threads , give it a try , might end up betterCommutate
Jon's answer works, you would just have to assign the value of i to a final local variable inside the loop. I would second the suggestion to look into using a ExecutorService though.Cockeye
C
10

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
         }
    });
}
Cardsharp answered 17/12, 2012 at 8:19 Comment(2)
I just gave some context regarding what I'm trying to do.Blest
@TerryLi: See my edit for how you can use my first approach within a loop. Or just use a named class...Cardsharp
S
5

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);
}
Spotlight answered 17/12, 2012 at 8:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.