ReentrantReadWriteLock 的例子

[quote]
两个线程 来改动 同一个 map里面的值, 在debug状态可以看到 , 只能同时一个线程 进行赋值, 因为有 writelock的 lock动作, 只有在一个lock 被unlock之后,才能另一线程 进入 进行修改。

同步阻塞

[/quote]




package com.base.concurrence.lock.reentrancereadwritelock;

public class ReentrancelockClient {
static LockBody lb = new LockBody();

public static void main(String[] args) {
RunningTask rt1 = new RunningTask("FIRST", "RMB");
RunningTask rt2 = new RunningTask("FIRST", "GBP");
Thread t1 = new Thread(rt1);
Thread t2 = new Thread(rt2);


LockBody.Wallet wt_1 = new LockBody.Wallet();
wt_1.currency = "JPY";

// LockBody.Wallet wt_2 = new LockBody.Wallet();
// wt_2.currency = "USD";

lb.store("FIRST", wt_1);
//lb.store("SECOND", wt_2);

t1.start();
t2.start();

try {
t1.join();
t2.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println(lb.getVal("FIRST").currency);
//System.out.println(lb.getVal("SECOND").currency);


}

static class RunningTask implements Runnable{

LockBody.Wallet newWt = new LockBody.Wallet();
String keyPoint, newCurrency;

public RunningTask(String key, String currency){
keyPoint = key;
newCurrency = currency;
}

@Override
public void run() {
lb.restore(keyPoint, newCurrency);
}

}


}







package com.base.concurrence.lock.reentrancereadwritelock;

import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class LockBody {

ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

public static Map<String, Wallet> mp = new TreeMap<String, Wallet>();


public void store(String key, Wallet wallet){
lock.writeLock().lock();
mp.put(key, wallet);
lock.writeLock().unlock();
}

public Wallet getVal(String key){
lock.readLock().lock();
Wallet wt = mp.get(key);
lock.readLock().unlock();
return wt;
}

public void restore(String key, String currency){
Wallet wallet = getVal(key);
lock.writeLock().lock();
wallet.currency = currency;
lock.writeLock().unlock();
}

public static class Wallet{
public String currency;
}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值