标签:
前面对线程安全与同步的基础知识已经具备基本的了解,但是不希望为了获得线程安全而去分析每次内存的访问,而希望线程的组件能够以安全的方式组合成更大的组件或程序。
1.确定对象状态是由哪些变量构成
2.确定限制状态变量的不变约束
3.指定一个管理并发对象状态的策略
public final class Counter{ private long value; public synchronized long getValue(){ return value; } public synchronized long increment() { if(value == Long.MAX_VALUE){ throw new IllegalStateException("counter overflow"); } return ++value; } }
public class PersonSet { private final Set<Person> mySet = new HashSet<>(); public synchronized boolean getMySet(Person p) { return mySet.contaions(p); } public synchronized void setMySet(Person p) { myset.add(p); } }
Collections的synchronizedList方法:
public static <T> List<T> synchronizedList(List<T> list)返回由指定列表支持的同步(线程安全的)列表。为了保证按顺序访问,必须通过返回的列表完成对底层列表的所有访问。
在返回的列表上进行迭代时,强制用户手工在返回的列表上进行同步:
List list = Collections.synchronizedList(new ArrayList()); ... synchronized(list) { Iterator i = list.iterator(); // Must be in synchronized block while (i.hasNext()) foo(i.next()); }
不遵从此建议将导致无法确定的行为。
如果指定列表是可序列化的,则返回的列表也将是可序列化的。
参数:
list - 被“包装”在同步列表中的列表。
返回:
指定列表的同步视图。
public class StringSet { private Object object = new Object(); private final Set<String> mySet = new HashSet<>(); public synchronized void setMySet(String p) { synchronized(object){ mySet.add(p); } } }
public class StringSet { private String tag ; private Map<String, String> locations = new HashMap<String, String>(); }
public class MutablePoint { public int x,y; public MutablePoint() { x = 0 ; y = 0; } public MutablePoint(MutablePoint p) { this.x = p.x; this.y = p.y; } } public class MonitorVehicleTracker { private final Map<String, MutablePoint> locations ; public MonitorVehicleTracker(Map<String, MutablePoint> locations) { this.locations = deepCopy(locations); } public synchronized Map<String, MutablePoint> getLocations() { return locations; } public synchronized MutablePoint getLocation(String id) { MutablePoint point = locations.get(id); return point == null ?null : new MutablePoint(point); } public synchronized void setLocation(String id ,int x , int y) { MutablePoint point = locations.get(id); if (point == null) { throw new IllegalArgumentException("no such id:" + id); } point.x = x; point.y = y; } /** * 深度克隆,不返回原有的数据 */ private Map<String, MutablePoint> deepCopy(Map<String, MutablePoint> loMap) { Map<String, MutablePoint> lo = new HashMap<String, MutablePoint>(); for (String id : loMap.keySet()) { lo.put(id, new MutablePoint(loMap.get(id))); } return Collections.unmodifiableMap(lo); } }
public class MutablePoint { public final int x,y; public MutablePoint(int x, int y) { this.x = x; this.y = y; } } public class MonitorVehicleTracker { private final ConcurrentHashMap<String, MutablePoint> locations ; private final Map<String, MutablePoint> unmodifiableMap ; public MonitorVehicleTracker(Map<String, MutablePoint> points) { //创建一个与给定映射具有相同映射关系的新映射。使用给定映射中映射关系数两倍的容量或 11(选更大的那一个)、默认加载因子和 concurrencyLevel 来创建该映射。 locations = new ConcurrentHashMap<>(points); // 返回指定映射的不可修改视图。 unmodifiableMap = Collections.unmodifiableMap(locations); } public Map<String, MutablePoint> getLocations() { return unmodifiableMap; } public MutablePoint getLocation(String id) { return locations.get(id); } public void setLocation(String id ,int x , int y) { if (locations.replace(id, new MutablePoint(x,y)) == null) { throw new IllegalArgumentException("invalid vehicle name:" + id); } } }
public Map<String, MutablePoint> getLocations(){ return Collections.unmodifiableMap(new HashMap<>(locations)); }
public class VisualComponet { //CopyOnWriteArrayList: //这一般需要很大的开销,但是当遍历操作的数量大大超过可变操作的数量时,这种方法可能比其他替代方法更 有效。在不能或不想进行同步遍历,但又需要从并发线程中排除冲突时,它也很有用。 private final List<KeyListener> keyListener = new CopyOnWriteArrayList<>(); private final List<MouseListener> mouseListener = new CopyOnWriteArrayList<>(); public void addKeyListener(KeyListener listener) { keyListener.add(listener); } public void addMouseListener(MouseListener listener) { mouseListener.add(listener); } public void removeKeyListener(KeyListener listener) { keyListener.remove(listener); } public void removeMouseListener(MouseListener listener) { mouseListener.remove(listener); } }
public class NumberRange { private final AtomicInteger lower = new AtomicInteger(); private final AtomicInteger upper = new AtomicInteger(); public void setLower(int i){ if (i > upper.get()) { throw new IllegalArgumentException("cant‘t set lower to " + i + "> upper"); } lower.set(i); } public void setUpper(int i){ if (i < lower.get()) { throw new IllegalArgumentException("cant‘t set upper to " + i + " < lower"); } upper.set(i); } public boolean isInRange (int i) { return (i >= lower.get() && i <= upper.get()); } }
public class SafePoint { private int x,y; private SafePoint(int[] a) { this(a[0],a[1]); } public SafePoint(int x, int y) { this.x = x; this.y = y; } public SafePoint (SafePoint point) { this(point.get()); } public synchronized int[] get() { return new int[]{x,y}; } public synchronized void set(int x,int y){ this.x = x; this.y = y; } } 通过修改point来实现: public class MonitorVehicleTracker { private final ConcurrentHashMap<String, SafePoint> locations ; private final Map<String, SafePoint> unmodifiableMap ; public MonitorVehicleTracker(Map<String, SafePoint> points) { //创建一个与给定映射具有相同映射关系的新映射。使用给定映射中映射关系数两倍的容量或 11(选更大的那一个)、默认加载因子和 concurrencyLevel 来创建该映射。 locations = new ConcurrentHashMap<>(points); // 返回指定映射的不可修改视图。 unmodifiableMap = Collections.unmodifiableMap(locations); } public Map<String, SafePoint> getLocations() { return unmodifiableMap; } public SafePoint getLocation(String id) { return locations.get(id); } public void setLocation(String id ,int x , int y) { if (!locations.contains(id)) { throw new IllegalArgumentException("invalid vehicle name:" + id); } locations.get(id).set(x, y); } }
public class Test{ public List<String> list = Collections.synchronizedList(new ArrayList<String>()); public synchronized void putIfAbsent(String str ){ if (!list.contains(str)) { list.add(str); } } }
public class Test{ public List<String> list = Collections.synchronizedList(new ArrayList<String>()); public synchronized void putIfAbsent(String str ){ synchronized (list) { if (!list.contains(str)) { list.add(str); } } } }
public class ImproveList<T> implements List<T> { private final List<T> list = new ArrayList<T>(); public ImproveList(List<T> list ) { this.list = list; } public synchronized void putIfAbsent(T t ){ if (!list.contains(t)) { list.add(t); } } }
标签:
原文地址:http://www.cnblogs.com/yeziTesting/p/4983646.html