利用读写锁(ReentrantReadWriteLock) 可实现对临界资源多线程时读写控制
class M
{
private static Map<Integer,String> map = new HashMap<Integer,String>();
private static M m = new M(map);
public static M getInstance()
{
return m;
}
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private final Lock r = lock.readLock();
private final Lock w = lock.writeLock();
public M(Map<Integer,String> map) {
this.map = map;
}
public String 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();
}
return map.put(key, value);
} finally {
w.unlock();
}
}
public String 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();
}
return map.get(key);
} finally {
r.unlock();
}
}
}
public class CheckCloneable implements Runnable
{
private int i;
private boolean get;
CheckCloneable(int i,boolean get)
{
this.i = i;
this.get = get;
}
public void run()
{
M m = M.getInstance();
if(get)
{
m.get(new Integer(1));
}
else
{
m.put(new Integer(1), "1");
}
}
public static void main(String[] args)
{
boolean getfirst = false;
CheckCloneable c = new CheckCloneable(0,getfirst);
Thread t = new Thread(c);
t.start();
CheckCloneable c2 = new CheckCloneable(1,getfirst);
Thread t2 = new Thread(c2);
t2.start();
}
}