this question is probably pretty easy to answer but I just don't get it. I reduced my problem until this little piece of code was left in order to find the "origin" of this problem: I'm trying to fill an ArrayList of Threads with a loop.
public static int u=0;
public void test(){
while (u <10) {
synchronized(threadList){
threadList.add(u, new Thread(){
@Override public void run(){
System.out.println("Thread at Index: " + u);
}
});
}
u++;
}
threadList.get(2).start();
}
With the last line I wanted to test the loop above by starting the thread at Index '2'. I'm expecting the console to show "Thread at Index: 2" but instead this is shown: "Thread at Index: 10" No matter which integer I write in the ".get(int)"-method, I receive the index '10'.
Why is that? And how to fix this?
The creation of the threads seems to work...so is the integer 'u' the problem?
I appreciate any kind of help! Thanks in advance!
uis static, so you'll always get current value (10when your program runs). You're not saving the value you used when creating the Thread anywhere.