multithreading - Java - Filling an ArrayList of Threads with loop -
this question pretty easy answer don't it. reduced problem until little piece of code left in order find "origin" of problem: i'm trying fill arraylist of threads 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 @ index: " + u); } }); } u++; } threadlist.get(2).start(); } with last line wanted test loop above starting thread @ index '2'. i'm expecting console show "thread @ index: 2" instead shown: "thread @ index: 10" no matter integer write in ".get(int)"-method, receive index '10'.
why that? , how fix this?
the creation of threads seems work...so integer 'u' problem?
i appreciate kind of help! in advance!
when reference u in run method
@override public void run(){ system.out.println("thread @ index: " + u); } the current value of u retrieved. @ end of loop , when thread runs, value 10.
try following
public static int u = 0; public void test(){ while (u <10) { synchronized(threadlist){ threadlist.add(u, new thread(){ int = u; @override public void run(){ system.out.println("thread @ index: " + i); } }); } u++; } threadlist.get(2).start(); } in anonymous thread class, you're setting instance field i value u has when constructor called , printing value when run() executed.
you reference u in context hasn't been executed yet, thread. when run() method gets called, program evaluate variable u, @ point in execution of program, value 10. if, instead, above, variable i hold value @ exact moment. because when new thread gets started , executed, field initialization occurs , u evaluated right away.
Comments
Post a Comment