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();

    }

  • 相关阅读:
    【转】ASP.NET MVC 使用 FluentScheduler 定时器计划任务
    【转】prototype扩展的JavaScript常用函数库
    【转】JavaScript系列文章:自动类型转换
    【转】Open Live Writer 插件更新
    highcharts与highstock实例
    SQL SERVER数据类型与C#数据类型对照表
    Highcharts在IE中不能一次性正常显示的一种解决办法
    MIME类型大全
    几种工具反编译被编译好的DLL文件
    MySQL之数据库的操作
  • 原文地址:https://www.cnblogs.com/kevinge/p/1800545.html
Copyright © 2011-2022 走看看