14 ReentrantReadWriteLock案例

  1. 分别在不同的方法中给读,写分别加锁
    class Count{
    private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
    //加读锁
    public void get(){
    rwl.readLock().lock();//其它线程只能读,不能写
    try{
    //业务操作
    }catch(InterruptedeException e ){
    //…
    }finally{
    rwl.readLock.unLock();//释放锁
    }

    }

//加写锁
public void put(){

rwl.writeLock().lock();//	阻塞其它的读,写线程
try{
	//业务操作

}catch(InterruptedException e)
//输出错误堆栈信息
} finally{
rwl.readLock().unLock();//解锁操作
}

public void static main(String[] args){

final Count count = new Count();
for(int i =0 ;i<2;i++){
	new Thread(){
		public void run(){
			//业务操作
			count.get();
		}
	}.start();

}

for(int i=0;i<2;i++){
new Thread(){
public void run(){
//业务操作
count.put();
}
}
}

}

}
2. 从以上的代码中,可以看到,读的时候是可以并发读取的,但是在写入的时候会对其它的读,写线程进行排斥操作。

你可能感兴趣的:(并发编程)