zoukankan      html  css  js  c++  java
  • 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();

    }

  • 相关阅读:
    设定cookie 获取cookie数据的转换
    cookie cookie的获取
    常见的请求方式 json字符串
    请求报文和响应报文
    http协议
    php分页查询 子查询
    MAC 地址为什么不需要全球唯一
    ceph分布式存储简介
    一文看懂为什么边缘计算是大势所趋
    真香!Windows 可直接运行 Linux 了
  • 原文地址:https://www.cnblogs.com/kevinge/p/1800545.html
Copyright © 2011-2022 走看看