问题描述
请教个问题,在多线程运用中,如果只加写锁,没有加读锁,那么在写的过程中,读线程可不可以读数据。
解决方案
解决方案二:
读线程可用.
解决方案三:
如果你不加读锁,那么就不会受到写锁的限制。也就是说读线程可以读数据。看下面我写的简单例子importjava.util.concurrent.locks.ReentrantReadWriteLock;importjava.util.concurrent.locks.Lock;publicclassTestReadWriteLock{publicstaticvoidmain(String[]args)throwsInterruptedException{ReadWriteDatarwd=newReadWriteData();ReadThreadrt=newReadThread(rwd);WriteThreadwt=newWriteThread(rwd);wt.start();Thread.sleep(2000);rt.start();}}classReadThreadextendsThread{privateReadWriteDatarwd;publicReadThread(ReadWriteDatarwd){this.rwd=rwd;}publicvoidrun(){System.out.println("result:"+rwd.getResult());}}classWriteThreadextendsThread{privateReadWriteDatarwd;publicWriteThread(ReadWriteDatarwd){this.rwd=rwd;}publicvoidrun(){rwd.setResult();}}classReadWriteData{privateReentrantReadWriteLockrwl=newReentrantReadWriteLock();privateLockreadLock=rwl.readLock();privateLockwriteLock=rwl.writeLock();privateinta=0;publicintgetResult(){//readLock.lock();try{System.out.println("ReadingStart...");returna;}finally{//readLock.unlock();}}publicvoidsetResult(){writeLock.lock();try{System.out.println("WritingStart...");Thread.sleep(10000);a++;System.out.println("WritingEnd...");}catch(InterruptedExceptione){}finally{writeLock.unlock();}}}
解决方案四:
引用2楼ok350350的回复:
如果你不加读锁,那么就不会受到写锁的限制。也就是说读线程可以读数据。看下面我写的简单例子importjava.util.concurrent.locks.ReentrantReadWriteLock;importjava.util.concurrent.locks.Lock;publicclassTestReadWriteLock{publicstaticvoidmain(String[]args)throwsInterruptedException{ReadWriteDatarwd=newReadWriteData();ReadThreadrt=newReadThread(rwd);WriteThreadwt=newWriteThread(rwd);wt.start();Thread.sleep(2000);rt.start();}}classReadThreadextendsThread{privateReadWriteDatarwd;publicReadThread(ReadWriteDatarwd){this.rwd=rwd;}publicvoidrun(){System.out.println("result:"+rwd.getResult());}}classWriteThreadextendsThread{privateReadWriteDatarwd;publicWriteThread(ReadWriteDatarwd){this.rwd=rwd;}publicvoidrun(){rwd.setResult();}}classReadWriteData{privateReentrantReadWriteLockrwl=newReentrantReadWriteLock();privateLockreadLock=rwl.readLock();privateLockwriteLock=rwl.writeLock();privateinta=0;publicintgetResult(){//readLock.lock();try{System.out.println("ReadingStart...");returna;}finally{//readLock.unlock();}}publicvoidsetResult(){writeLock.lock();try{System.out.println("WritingStart...");Thread.sleep(10000);a++;System.out.println("WritingEnd...");}catch(InterruptedExceptione){}finally{writeLock.unlock();}}}
回答的非常好
解决方案五:
如果你要读取两个变量或者以上的,或者线程不安全的集合或任何东西,那么读线程不加锁很可能会导致读出的数据之间不匹配,导致运算错误。危险!
解决方案六:
读写锁,读写互斥,写写互斥,读读不互斥。简单来讲,可以并发读取,但是,写入时不能读,不能同时写。
解决方案七:
引用5楼preferme的回复:
读写锁,读写互斥,写写互斥,读读不互斥。简单来讲,可以并发读取,但是,写入时不能读,不能同时写。
说的很好的。
解决方案八:
可以读,你用程序往记事本里写东西的时候你可以打开这个文件看内容的,程序就更不用说了能读。但是读的内容不全可能会有问题