美文网首页
2019-10-12

2019-10-12

作者: 九度_09e3 | 来源:发表于2019-10-12 10:53 被阅读0次

    可重入读写锁

    代码:

    packagecom.mobin.thread.Lock;

    importsun.dc.pr.PRError;

    importsun.security.provider.SHA;

    importjava.util.HashMap;

    importjava.util.Map;

    importjava.util.concurrent.CountDownLatch;

    importjava.util.concurrent.CyclicBarrier;

    importjava.util.concurrent.locks.Lock;

    importjava.util.concurrent.locks.ReentrantLock;

    importjava.util.concurrent.locks.ReentrantReadWriteLock;

    publicclassReentReadWriteLock{

    privatestaticReentrantReadWriteLocklock=newReentrantReadWriteLock();

    privatestaticReentrantReadWriteLock.WriteLockwriteLock=lock.writeLock();

    privatestaticReentrantReadWriteLock.ReadLockreadLock=lock.readLock();

    //private static Lock lock = new ReentrantLock();

    privatestaticMapmaps=newHashMap<>();

    privatestaticCountDownLatchlatch=newCountDownLatch(102);

    privatestaticCyclicBarriercyclicBarrier=newCyclicBarrier(102);

    publicstaticvoidmain(String[]args)throwsInterruptedException{

    longbenginTime=System.currentTimeMillis();

    for(inti=0; i<100; i++){

    newThread(newReadThread()).start();

            }

    for(inti=0; i<100; i++){

    newThread(newWriteThread()).start();

            }

    latch.await();

    longendTime=System.currentTimeMillis();

    System.out.println("Consumer Time is"+(endTime-benginTime)+"ms");

        }

    staticclassWriteThreadimplementsRunnable{

    @Override

    publicvoidrun() {

    try{

    cyclicBarrier.await();

    }catch(Exceptione){

    e.printStackTrace();

                }

    try{

    writeLock.lock();

    maps.put("1","2");

    Thread.sleep(100);

    }catch(Exceptione){

    e.printStackTrace();

    }finally{

    writeLock.unlock();

                }

    latch.countDown();

            }

        }

    staticclassReadThreadimplementsRunnable{

    @Override

    publicvoidrun() {

    try{

    cyclicBarrier.await();

    }catch(Exceptione){

    e.printStackTrace();

                }

    try{

    readLock.lock();

    maps.get("1");

    Thread.sleep(100);

    }catch(Exceptione){

    e.printStackTrace();

    }finally{

    readLock.unlock();

                }

    latch.countDown();

            }

        }

    }

    相关文章

      网友评论

          本文标题:2019-10-12

          本文链接:https://www.haomeiwen.com/subject/dixqmctx.html