ReentrantReadWriteLock 的例子
程序员文章站
2022-03-09 18:57:56
...
[quote]
两个线程 来改动 同一个 map里面的值, 在debug状态可以看到 , 只能同时一个线程 进行赋值, 因为有 writelock的 lock动作, 只有在一个lock 被unlock之后,才能另一线程 进入 进行修改。
同步阻塞
[/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;
}
}
上一篇: PHP如何实现表格Excel的导出
下一篇: php安装curl扩展的方法