• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
开水房
ASP.NET
博客园    首页    新随笔    联系   管理    订阅  订阅
java 多线程 读写锁

利用读写锁(ReentrantReadWriteLock) 可实现对临界资源多线程时读写控制

 

class M

{

private static Map<Integer,String> map = new HashMap<Integer,String>();  

private static M m = new M(map);

public static M getInstance()

{

return m;

}

    private final ReadWriteLock lock = new ReentrantReadWriteLock();  

    private final Lock r = lock.readLock();  

    private final Lock w = lock.writeLock();  

    public M(Map<Integer,String> map) {  

        this.map = map;  

    }  

    public String put(Integer key, String value) {  

     System.out.println("waiting put");

        w.lock();  

        try { 

         System.out.println("processing put");

         try {

Thread.sleep(5000l);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

            return map.put(key, value);  

        } finally {  

            w.unlock();  

        }  

    }  

 

    public String get(Object key) {  

     System.out.println("waiting get");

        r.lock();  

        try {

         System.out.println("processing get");

         try {

Thread.sleep(5000l);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

            return map.get(key);  

        } finally {  

            r.unlock();  

        }  

    }  

  

}

public class CheckCloneable implements Runnable

{

private int i;

private boolean get;

CheckCloneable(int i,boolean get)

{

this.i = i;

this.get = get;

}

public void run()

{

M m = M.getInstance();

if(get)

{

m.get(new Integer(1));

}

else

{

m.put(new Integer(1), "1");

}

}

public static void main(String[] args)

{

boolean getfirst = false;

CheckCloneable c = new CheckCloneable(0,getfirst);

Thread t = new Thread(c);

t.start();

CheckCloneable c2 = new CheckCloneable(1,getfirst);

Thread t2 = new Thread(c2);

t2.start();

}

} 

posted on 2010-08-16 11:26  白开水皮皮  阅读(531)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3