packagenum10;importjava.util.HashMap;importjava.util.Map;importjava.util.concurrent.locks.Lock;importjava.util.concurrent.locks.ReentrantReadWriteLock;//java 读写锁
classM
{private static Map map = new HashMap();private static M m = newM(map);public staticM getInstance()
{returnm;
}private final java.util.concurrent.locks.ReadWriteLock lock = newReentrantReadWriteLock();private final Lock r =lock.readLock();private final Lock w =lock.writeLock();public M(Mapmap) {this.map =map;
}publicString put(Integer key, String value) {
System.out.println("waiting put");
w.lock();try{
System.out.println("processing put");try{
Thread.sleep(5000l);
}catch(InterruptedException e) {//TODO Auto-generated catch block
e.printStackTrace();
}returnmap.put(key, value);
}finally{
System.out.println("put finish");
w.unlock();
}
}public synchronizedString put1(Integer key, String value) {
System.out.println("waiting put1");try{
System.out.println("processing put1");try{
Thread.sleep(5000l);
}catch(InterruptedException e) {//TODO Auto-generated catch block
e.printStackTrace();
}returnmap.put(key, value);
}finally{
System.out.println("put1 finish");
}
}publicString get(Object key) {
System.out.println("waiting get");
r.lock();try{
System.out.println("processing get");try{
Thread.sleep(5000l);
}catch(InterruptedException e) {//TODO Auto-generated catch block
e.printStackTrace();
}returnmap.get(key);
}finally{
System.out.println("get finish");
r.unlock();
}
}public synchronizedString get1(Object key) {
System.out.println("waiting get1");try{
System.out.println("processing get1");try{
Thread.sleep(5000l);
}catch(InterruptedException e) {//TODO Auto-generated catch block
e.printStackTrace();
}returnmap.get(key);
}finally{
System.out.println("get1 finish");
}
}
}public class ReadWriteLock implementsRunnable
{private inti;private booleanget;
ReadWriteLock(int i, booleanget)
{this.i =i;this.get =get;
}public voidrun()
{
M m=M.getInstance();if(get)
{
m.get1(new Integer(1));
}else{
m.put1(new Integer(1), "1");
}
}public static voidmain(String[] args)
{boolean getfirst = false;
ReadWriteLock c= new ReadWriteLock(0, !getfirst);
Thread t= newThread(c);
t.start();
ReadWriteLock c2= new ReadWriteLock(1, getfirst);
Thread t2= newThread(c2);
t2.start();
}
}