java lock用法_Java Lock的使用

packagecom.zxd.concurrent.learning;importjava.util.concurrent.locks.ReentrantReadWriteLock;/***@authorCoderZZ

* @Title: ${FILE_NAME}

* @Project: ConcurrentLearning

* @Package com.zxd.concurrent.learning

* @description: 读锁不互斥;读写、写写互斥

* @Version 1.0

* @create 2018-04-08 21:29

**/

public classReentrantReadWriteLockTest {private ReentrantReadWriteLock reentrantReadWriteLock = newReentrantReadWriteLock();public voidread(){try{

reentrantReadWriteLock.readLock().lock();

System.out.println("获得读锁"+Thread.currentThread().getName()+" timestamp:"+System.currentTimeMillis());

Thread.sleep(10000);

}catch(InterruptedException e) {

e.printStackTrace();

}finally{

reentrantReadWriteLock.readLock().unlock();

}

}public voidwrite(){try{

reentrantReadWriteLock.writeLock().lock();

System.out.println("获得写锁"+Thread.currentThread().getName()+" timestamp:"+System.currentTimeMillis());

Thread.sleep(10000);

}catch(Exception e){

e.printStackTrace();

}finally{

reentrantReadWriteLock.writeLock().unlock();

}

}public static voidmain(String[] args){

ReentrantReadWriteLockTest reentrantReadWriteLockTest= newReentrantReadWriteLockTest();

Runnable readRunnable= newRunnable() {

@Overridepublic voidrun() {

reentrantReadWriteLockTest.read();

}

};

Thread threadA= newThread(readRunnable);

threadA.setName("A");

threadA.start();

Thread threadB= newThread(readRunnable);

threadB.setName("B");

threadB.start();

Runnable writeRunnable= newRunnable() {

@Overridepublic voidrun() {

reentrantReadWriteLockTest.write();

}

};

Thread writeA= newThread(writeRunnable);

writeA.setName("writeA");

writeA.start();

Thread writeB= newThread(writeRunnable);

writeB.setName("writeB");

writeB.start();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值