这个是上读写锁的部分
public class LockMap {
private static HashMap<String,Object> map=new HashMap<String, Object>();
private static ReentrantReadWriteLock lock=new ReentrantReadWriteLock();
private static Lock read=lock.readLock();
private static Lock write=lock.writeLock();
public Object get(String key) throws InterruptedException {
read.lock();
try{
Object obj=map.get(key);
return obj;
}finally {
read.unlock();
}
}
public void put(String key,Object value) throws InterruptedException {
write.lock();
try{
map.put(key,value);
}finally {
write.unlock();
}
}
}
这是创建线程运行的部分
public class LockMapTest {
private static SimpleDateFormat format=new SimpleDateFormat("HH:mm:ss:sss");
private static LockMap map=new LockMap();
public static void main(String[] args) throws InterruptedException {
new Thread(new Runner("w"),"Write-Thread1").start();
new Thread(new Runner("r"),"Read-Thread1").start();
new Thread(new Runner("r"),"Read-Thread2").start();
new Thread(new Runner("r"),"Read-Thread3").start();
new Thread(new Runner("r"),"Read-Thread4").start();
}
public static class Runner implements Runnable{
private String readWrite;
public Runner(String readWrite){
this.readWrite=readWrite;
}
public void run() {
while (true){
if ("w".equals(readWrite)){
try {
System.out.println(format.format(new Date())+" Current thread "+Thread.currentThread().getName()+" writing ");
map.put("first",UUID.randomUUID().toString());
} catch (InterruptedException e) {
e.printStackTrace();
}
}else if ("r".equals(readWrite)){
try {
System.out.println(format.format(new Date())+" Current thread "+Thread.currentThread().getName()+" get value "+map.get("first"));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
运行以后,线程运行效果图