5 锁
java多线程里面,我们知道可以使用synchronized关键字来实现线程间的同步互斥工作,那么其实还有一个更优秀的机制去完成这个“同步互斥”工作,他就是Lock对象,典型的有重入锁和读写锁。他们具有比synchronized更为强大的功能,并且有嗅探锁定、多路分支等功能。
(1)ReentrantLock重入锁
重入锁,在需要进行同步的代码部分加上锁定,但是一定不要忘记最后一定要释放锁定,不然会造成锁永远无法释放,其他线程永远进不来的结果。
一般在使用ReentrantLock就会使用finally,在finally方法块中释放锁
private Lock lock = new ReentrantLock();
public void method1(){
try {
lock.lock();
System.out.println("当前线程:" + Thread.currentThread().getName() + "进入method1...");
Thread.sleep(1000);
System.out.println("当前线程:" + Thread.currentThread().getName() + "退出method1...");
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}finally{
lock.unlock();
}
}
(2)锁与等待/通知 Condition
Condition类似于在使用synchronized进行多线程通信时用的wait()与notify(),Condition就是使用Lock进行多线程通信的时候的对象。Condition是针对lock对象的。
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void method1(){
try {
lock.lock();
System.out.println("当前线程:" + Thread.currentThread().getName() + "进入method1...");
Thread.sleep(1000);
System.out.println("当前线程:" + Thread.currentThread().getName() + "释放锁.");
condition.await(); //进入等待,类似于使用synchronized时的wait();释放锁
System.out.println("当前线程:" + Thread.currentThread().getName() + "继续执行method1...");
System.out.println("当前线程:" + Thread.currentThread().getName() + "退出method1...");
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}finally{
lock.unlock();
}
}
public void method2(){
try {
lock.lock();
System.out.println("当前线程:" + Thread.currentThread().getName() + "进入method2...");
Thread.sleep(2000);
System.out.println("当前线程:" + Thread.currentThread().getName() + "退出method2...");
Thread.sleep(1000);
condition.signal(); //发出通知,类似于使用synchronized时的notify();不释放锁
} catch (Exception e) {
// TODO: handle exception
}finally{
lock.unlock();
}
}
(3)多 Condition
从一个lock对象获取多个Condition对象
UseManyCondition.java
package com.test.sync12; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class UseManyCondition { private Lock lock = new ReentrantLock(); private Condition c1 = lock.newCondition(); private Condition c2 = lock.newCondition(); public void m1(){ try { lock.lock(); System.out.println("当前线程:" + Thread.currentThread().getName() + "进入m1等待..."); c1.await(); System.out.println("当前线程:" + Thread.currentThread().getName() + "进入m1继续..."); } catch (Exception e) { // TODO: handle exception }finally{ lock.unlock(); } } public void m2(){ try { lock.lock(); System.out.println("当前线程:" + Thread.currentThread().getName() + "进入m2等待..."); c1.await(); System.out.println("当前线程:" + Thread.currentThread().getName() + "进入m2继续..."); } catch (Exception e) { // TODO: handle exception }finally{ lock.unlock(); } } public void m3(){ try { lock.lock(); System.out.println("当前线程:" + Thread.currentThread().getName() + "进入m3等待..."); c2.await(); System.out.println("当前线程:" + Thread.currentThread().getName() + "进入m3继续..."); } catch (Exception e) { // TODO: handle exception }finally{ lock.unlock(); } } public void m4(){ try { lock.lock(); System.out.println("当前线程:" + Thread.currentThread().getName() + "进入m4,唤醒c1..."); c1.signalAll(); } catch (Exception e) { // TODO: handle exception }finally{ lock.unlock(); } } public void m5(){ try { lock.lock(); System.out.println("当前线程:" + Thread.currentThread().getName() + "进入m5,唤醒c2..."); c2.signal(); } catch (Exception e) { // TODO: handle exception }finally{ lock.unlock(); } } public static void main(String[] args) throws Exception { final UseManyCondition umc = new UseManyCondition(); Thread t1 = new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub umc.m1(); } }, "t1"); Thread t2 = new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub umc.m2(); } }, "t2"); Thread t3 = new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub umc.m3(); } }, "t3"); t1.start(); t2.start(); t3.start(); Thread.sleep(2000); Thread t4 = new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub umc.m4(); } }, "t4"); t4.start(); Thread.sleep(2000); Thread t5 = new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub umc.m5(); } }, "t5"); t5.start(); } }
(4)Lock/Condition的其他方法
- 公平锁和非公平锁
Lock lock = new ReentrantLock(boolean isFair); isFair ? 公平锁 : 非公平锁;默认为非公平锁
公平锁是哪个先调用则先上锁,如果非公平锁则是按照CPU的调度自动上锁,非公平锁的效率高于公平锁。
ReentrantLock用法
- tryLock():尝试获得锁,获得结果用true/false返回,true表示能够获得,false表示不能获得
- isFair() : 是否是公平锁
- isLocked() : 是否锁定
- getHoldCount() : 查询当前线程保持此锁的个数,也就是调用lock()的次数
- lockInterruptibly():优先响应中断的锁
- getQueueLength():返回正在等待获取此锁定的线程数
- getWaitQueueLength():返回等待与锁定相关的给定条件Condition的线程数
- hasQueuedThread(Thread thread):查询指定的线程是否正在等待此锁
- hasQueuedThreads():查询是否有线程正在等待此锁
- hasWaiters():查询是否有线程正在等待与此锁定相关的condition条件
(5)ReentrantReadWriteLock(读写锁)
读写锁ReentrantReadWriteLock,其核心就是实现读写分离的锁。在高并发访问下,尤其是读多写少的情况下,性能要远高于重入锁。
之前学synchronized、ReentrantLock时,我们知道,同一时间内,只能有一个线程进行访问被锁定的代码,那么读写锁则不同,其本质是分成两个锁,即读锁和写锁。在读锁下,多个线程可以并发的进行访问,但是在写锁的时候,只能一个一个的顺序访问。
口诀:读读共享,写写互斥,读写互斥
private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
private ReadLock readLock = rwLock.readLock();
private WriteLock writeLock = rwLock.writeLock();
(6)锁的优化总结
- 避免死锁
- 减小锁的持有时间
- 减小锁的力度
- 锁的分离
- 尽量使用无锁的操作,如原子操作(Atomic系列类),volatile关键字