您的位置:首页 > 编程语言 > Java开发

Java Concurrency in Practice :基础知识(正确的同步 -- 客户端加锁)

2016-11-24 21:06 465 查看

正确的同步 -- 客户端加锁

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: