publicstaticvoidmodify(){//使用lock方法枷锁
lock.lock();try{
text +=" "+Thread.currentThread().getName();}catch(Exception e){
e.printStackTrace();}finally{//使用unlock方法解锁
lock.unlock();}}
1
2
3
4
5
6
7
8
9
10
11
12
13
1
2
3
4
5
6
7
8
9
10
11
12
13
加锁之后对多线程对text的修改最后的长度是一定的(这儿不能保证线程修改的顺序)。
3.8.2 ReentradLock方法介绍
ReentrandLock
作用
tryLock()
尝试获取锁
tryLock(long timeout, TimeUnit unit)
尝试获取锁,timeout是尝试获取锁的等待事件,超时不候,unit是等待时间的单位
unlock()
释放锁
getHoldCount()
当前线程持有该锁的次数
isHeldByCurrentThread()
当前线程是否持有该锁
…
…
3.8.3 ReentrandLock源码
构造方法
publicReentrantLock(){
sync =newNonfairSync();}/**
* Creates an instance of {@code ReentrantLock} with the
* given fairness policy.
* 如果fair为true则构造是一个公平锁
* @param fair {@code true} if this lock should use a fair ordering policy
*/publicReentrantLock(boolean fair){
sync = fair ?newFairSync():newNonfairSync();}