正确的同步 -- 客户端加锁
1、错误的示范
public class ListHepler<E>{
public List<E> list = Collections.synchronizedList(new ArrayList<E>);
public synchronized boolean putIfAbsent(E x){
boolean absent = !list.contains(x);
if(absent) list.add(x);
return absent;
}
}
}
2、正确的例子
public class ListHepler<E>{
public List<E> list = Collections.synchronizedList(new ArrayList<E>);
public boolean putIfAbsent(E x){
synchronized(list){
boolean absent = !list.contains(x);
if(absent) list.add(x);
return absent;
}
}
}
3、有啥区别?
第一段程序中synchronized加在了putIfAbsent方法上,同步的是对象x
而第二段程序中synchronized加在了putIfAbsent方法里,同步的是队列List