生活随笔
收集整理的這篇文章主要介紹了
Java并发编程实战 第4章 对象的组合
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Java監視器模式
java監視器模式就是在將共享的數據封裝在一個類里面,然后然后所有訪問或者修改這些數據的方法都標注為synchronize。
車輛追蹤模擬:
使用監視器模式:
CarTracker對象維護了一個所有汽車坐標的Map,這個Map是競爭資源,線程會同時對它進行更新和讀取。所以才每個方法上都加了synchronized。
package com.zjf; import java.util.*; //定義坐標 ?class Point{ ????public int x,y; ????public Point(Point p){ ????????this.x=p.x; ????????this.y=p.y; ????} } //車輛追蹤 public class CarTracker{ ???//維護所有車輛的坐標Map key是汽車的ID 這是競爭資源 ????private Map<String,Point> locations; ????public CarTracker(Map<String,Point> points){ ????????locations=deepCopy(points); ????} ????//獲得所有車輛的坐標Map ????public synchronized Map<String,Point> getLocations(){ ????????return deepCopy(locations); ????} ????//所有某一車輛的坐標 ????public synchronized Point getLocation(String id){ ????????Point p=locations.get(id); ????????return (p==null)?null:new Point(p); ????} ????//設置某一個汽車的坐標 ????public synchronized void setLocation(String id,int x,int y){ ????????Point p=locations.get(id); ????????if(p==null) ????????????System.out.print("id not exists"); ????????p.x=x; ????????p.y=y; ????} ????//深拷貝 ????public static Map<String,Point> deepCopy(Map<String,Point> m){ ????????Map<String,Point> result=new HashMap<String,Point>(); ????????for(String id:m.keySet()){ ????????????result.put(id,new Point(m.get(id))); ????????} ????????return Collections.unmodifiableMap(result); ????} } 使用java的并發集合來重寫上面的代碼:
package com.zjf; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; //定義坐標 這個是不可變類型 所以可以直接返回 不擔心被修改 class Point { ???public final int x, y; ???public Point(int x, int y) { ??????this.x = x; ??????this.y = y; ???} } // 車輛追蹤 public class CarTracker { ???// 維護所有車輛的坐標Map key是汽車的ID 這是競爭資源 使用ConcurrentMap ???private final ConcurrentMap<String, Point> locations; ???//是locations的視圖 locations的變化會直接映射到這里 但是它是不可修改的。 ???private final Map<String, Point> unmodifiableMap; ???public CarTracker(Map<String,Point> points){ ????????locations =new ConcurrentHashMap<String,Point>(points); ????????unmodifiableMap=Collections.unmodifiableMap(locations); ????} ???// 獲得所有車輛的坐標Map 結果是不可修改的 ???public Map<String,Point> getLocations(){ ????????return unmodifiableMap; ????} ???// 獲取某一車輛的坐標 結果也是不可修改的 ???public Point getLocation(String id){ ????????return locations.get(id); ????} ???// 設置某一個汽車的坐標 使用replace方法 這是ConcurrentMap提供的并發安全的方法 ???public void setLocation(String id,int x,int y){ ????????if(locations.replace(id,new Point(x,y))==null) ????????????System.out.print("id not exists"); ????} } 上面的方式,我們成為委托。我們把對車輛Map的并發管理委托給ConcurrentHashMap類。
轉載于:https://www.cnblogs.com/xiaolang8762400/p/7056055.html
總結
以上是生活随笔為你收集整理的Java并发编程实战 第4章 对象的组合的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。