My question is why I should use final to decorate the variable, list? It is used by the instance of an anonymous inner class Without final, it won't compile.
the code looks like this:
public class TwoThreadsOneListCurrModi
{
public static void main(String[] args)
{
final List<String> list = Collections.synchronizedList(new ArrayList<String>());
for (int i =0 ; i<20;i++)
list.add(String.valueOf(i));
Thread t1 = new Thread(new Runnable(){
@Override
public void run()
{
synchronize(list) {
System.out.println("size of list:" +list.size());
}
}
});
t1.start();
}
}
But if I use normal class, it is fine.
public class TwoThreadsOneListCurrModi2
{
public static void main(String[] args)
{
final List<String> list = Collections.synchronizedList(new ArrayList<String>());
initialize list;
Thread t1 = new WorkThread(list);
Thread t2 = new WorkThread(list);
t1.start();
t2.start();
}
}
class WorkThread extends Thread{
List<String> list;
public void run(){
do sth with list and synchronize block on list
}
Work1(List<String> list)
{ this.list = list; }
}