Reputation: 531
I am new to multithread programming. The code does not do what I want :
public class Test {
static int i;
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(10);
for(i = 0; i<10 ;i++) {
executor.execute(new Runnable() {
public void run () {
System.out.println(i);
}
});
}
}
}
output : 2 4 3 4 2 6 6 8 9 10
I expect it to output something like 0,1,2,3,4,5,6,7,8,9 with or without order. My question is what i can do to get my expected output, and how to make them in order.
Thanks in advance
Upvotes: 1
Views: 232
Reputation: 5424
Don't pass static i
to run
:
public class Test {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(10);
for(int i = 0; i < 10 ;i++){
int x = i;
executor.execute(new Runnable(){
public void run (){
System.out.println(x);
}
});
}
}
}
Upvotes: 2
Reputation: 72844
You can have a class that implements Runnable
and copy the static field into an instance field with a constructor:
executor.execute(new MyRunnable(i));
class MyRunnable implements Runnable {
int i;
public MyRunnable(int i) {
this.i = i;
}
// run method
}
This guarantees that each thread has its own unique integer with exactly the same order of i
in the for
loop.
Upvotes: 0