Reputation: 404
I have an anonymous class which takes the iterated value from a collection as shown below. With this code, is that immediate variable in
preserved within anonymous class? Or different threads can take same in
value?
List<Integer> list = new ArrayList<>();
for (int i = 1; i <= 20; i++)
list.add(i);
for (final Integer in : list) {
new Thread(new Runnable() {
@Override
public void run() {
Thread.sleep(1000);
System.out.println(value + "," + in);
}
}).start();
}
Upvotes: 1
Views: 61
Reputation: 178333
Yes, each value of in
is preserved in each of the Thread
s that is created. You can use a local variable in an anonymous inner class as long as it's declared final
, or if you're using Java 8, if it's "effectively final" (not final
but not changed).
Upvotes: 3