- synchronized为一个锁升级的过程,ReenTrantLock底层为CAS
- ReenTrantLock可以代替synchronized
- ReenTrantLock需要手动去释放锁
- ReenTrantLock可以设置公平或非公平
- ReenTrantLock可重入
- ReenTrantLock可以使用tryLock进行尝试锁定,不论锁定与否继续执行下面的代码
public class ReenTrantLockTest2 {
Lock lock = new ReentrantLock();
public void m1(){
try{
lock.lock();
for(int i = 0;i < 10;i++){
TimeUnit.SECONDS.sleep(1);
System.out.println(i);
}
}catch (InterruptedException e ){
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void m2() {
boolean flag = false;
try{
flag = lock.tryLock(5, TimeUnit.SECONDS);
System.out.println("m2结束"+flag);
}catch (InterruptedException e){
e.printStackTrace();
}finally {
if(flag){
lock.unlock();
}
}
}
public static void main(String[] args) {
ReenTrantLockTest2 reenTrantLockTest2 = new ReenTrantLockTest2();
new Thread(reenTrantLockTest2::m1).start();
try {
TimeUnit.SECONDS.sleep(1);
}catch (InterruptedException e){
e.printStackTrace();
}
new Thread(reenTrantLockTest2::m2).start();
//reenTrantLockTest.start();
}
}
- lock.lockInterruptibly来响应lock.interrupt 对还在等待获取锁的线程进行打断处理
-
public class ReenTrantLockTest3 { public static void main(String[] args) { Lock lock = new ReentrantLock(); Thread t1 = new Thread(new Runnable() { @Override public void run() { try{ System.out.println(Thread.currentThread().getName() + "开始获取锁"); lock.lockInterruptibly(); System.out.println(Thread.currentThread().getName() + "获取到锁"); //lock.lock(); for(int i = 0; i < 20;i++){ TimeUnit.SECONDS.sleep(2); System.out.println(Thread.currentThread().getName() +"----->"+ i); } }catch (InterruptedException e){ //e.printStackTrace(); System.out.println("线程被中断了"); }finally { try{ lock.unlock(); }catch (Exception e){ System.out.println("线程执行完毕"); } } } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { try{ System.out.println(Thread.currentThread().getName() + "开始获取锁"); TimeUnit.SECONDS.sleep(3); lock.lockInterruptibly(); System.out.println(Thread.currentThread().getName() + "获取到锁"); }catch (InterruptedException e){ //e.printStackTrace(); System.out.println(Thread.currentThread().getName()+"线程被中断了"); }finally { try{ lock.unlock(); }catch (Exception e){ System.out.println("线程执行完毕"); } } } }); t1.start(); try { TimeUnit.SECONDS.sleep(2); }catch (InterruptedException e){ e.printStackTrace(); } t2.start(); t2.interrupt(); } }