可重入读写锁
代码:
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();
}
}
}
网友评论