java 同步 lock_java 同步synchronized,lock(obj) ,读写锁

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();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值