代码1:
[code="java"]@NotThreadSafe
class BadListHelper {
public List list = Collections.synchronizedList(new ArrayList());
public synchronized boolean putIfAbsent(E x) {
boolean absent = !list.contains(x);
if (absent)
list.add(x);
return absent;
}
}
@ThreadSafe
public class ImprovedList implements List {
private final List list;
/**
* PRE: list argument is thread-safe.
*/
public ImprovedList(List<T> list) { this.list = list; }
public synchronized boolean putIfAbsent(T x) {
boolean contains = list.contains(x);
if (contains)
list.add(x);
return !contains;
}
}
[/code]
代码1不是线程安全的,而代码二是线程安全的 (最上面的是代码1,最后的代码是代码我)
二者的区别主要是final 修饰了list ,而final 如果指向引用的话,引用不可变,而所指向的引用是可以变化的
[b]
为什么代码1不是线程安全的,而代码2是线程安全的[/b]