下面是我给你写的代码 你自己读读 就明白
package num10;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
// java 读写锁
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 java.util.concurrent.locks.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 {
System.out.println("put finish");
w.unlock();
}
}
public synchronized String 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();
}
return map.put(key, value);
} finally {
System.out.println("put1 finish");
}
}
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 {
System.out.println("get finish");
r.unlock();
}
}
public synchronized String 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();
}
return map.get(key);
} finally {
System.out.println("get1 finish");
}
}
}
public class ReadWriteLock implements Runnable
{
private int i;
private boolean get;
ReadWriteLock(int i, boolean get)
{
this.i = i;
this.get = get;
}
public void run()
{
M m = M.getInstance();
if (get)
{
m.get1(new Integer(1));
}
else
{
m.put1(new Integer(1), "1");
}
}
public static void main(String[] args)
{
boolean getfirst = false;
ReadWriteLock c = new ReadWriteLock(0, !getfirst);
Thread t = new Thread(c);
t.start();
ReadWriteLock c2 = new ReadWriteLock(1, getfirst);
Thread t2 = new Thread(c2);
t2.start();
}
}
运行结果如下:
waiting get1
processing get1
get1 finish
waiting put1
processing put1
put1 finish
可以看出synchronized 关键字相当于 lock(M.class), 是将整个对象锁住,为提高效率,可以使用读写锁
|