JAVA中的锁

 2022-09-19
原文地址:https://blog.51cto.com/caofanqi/5014180

JAVA中的锁

一、重入锁

重入锁,也叫做递归锁,指的是同一线程 外层函数获得锁之后 ,内层递归函数仍然有获取该锁的代码,但不受影响。在JAVA环境下 ReentrantLock 和synchronized 都是 可重入锁。这里主要来看ReentrantLock。

ReentrantLock: 在需要进行同步的代码部分加上锁定,但不要忘记最后一定要释放锁定, 不然会造成锁永远无法释放,其他线程永远进不来的结果。

简单使用:

    public class UseReentrantLock {
    
      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 (InterruptedException e) {
          e.printStackTrace();
        } 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);
        } catch (InterruptedException e) {
          e.printStackTrace();
        } finally {
    
          lock.unlock();
        }
      }
    
      public static void main(String[] args) {
    
        final UseReentrantLock ur = new UseReentrantLock();
        Thread t1 = new Thread(() -> {
          ur.method1();
          ur.method2();
        }, "t1");
    
        t1.start();
        try {
          Thread.sleep(10);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }

在使用synchronized的时候,如果需要多线程间进行协调工作则需要Object的wait()和notify()、notifyAll()方法配合工作。那么同样,在使用Lock的时候,可以使用一个新的等待/通知的类,他就是Condition。这个Condition一定是针对具体某一把锁的。也就是在只有锁的基础上才会产生Condition。

使用单个Condition:

    public class UseCondition {
    
      private Lock lock = new ReentrantLock();
      private Condition condition = lock.newCondition();
    
      public void method1() {
        try {
          lock.lock();
          System.out.println("当前线程:" + Thread.currentThread().getName() + "进入等待状态..");
          Thread.sleep(3000);
          System.out.println("当前线程:" + Thread.currentThread().getName() + "释放锁..");
          condition.await(); // 类似于 wait
          System.out.println("当前线程:" + Thread.currentThread().getName() + "继续执行...");
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          lock.unlock();
        }
      }
    
      public void method2() {
        try {
          lock.lock();
          System.out.println("当前线程:" + Thread.currentThread().getName() + "进入..");
          Thread.sleep(3000);
          System.out.println("当前线程:" + Thread.currentThread().getName() + "发出唤醒..");
          condition.signal(); // 类似于 notify
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          lock.unlock();
        }
      }
    
      public static void main(String[] args) {
    
        final UseCondition uc = new UseCondition();
        Thread t1 = new Thread(new Runnable() {
          @Override
          public void run() {
            uc.method1();
          }
        }, "t1");
        Thread t2 = new Thread(new Runnable() {
          @Override
          public void run() {
            uc.method2();
          }
        }, "t2");
        t1.start();
    
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        t2.start();
      }
    
    }

使用多个Condition:可以通过一个Lock对象产生多个Condition进行多线程间的交互,非常的灵活。可以使得部分需要唤醒的线程唤醒,其他线程则继续等待通知

    public class UseManyCondition {
    
      private ReentrantLock 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) {
          e.printStackTrace();
        } 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) {
          e.printStackTrace();
        } 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) {
          e.printStackTrace();
        } finally {
          lock.unlock();
        }
      }
    
      public void m4() {
        try {
          lock.lock();
          System.out.println("当前线程:" + Thread.currentThread().getName() + "唤醒..");
          c1.signalAll();
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          lock.unlock();
        }
      }
    
      public void m5() {
        try {
          lock.lock();
          System.out.println("当前线程:" + Thread.currentThread().getName() + "唤醒..");
          c2.signal();
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          lock.unlock();
        }
      }
    
      public static void main(String[] args) {
    
        final UseManyCondition umc = new UseManyCondition();
        Thread t1 = new Thread(new Runnable() {
          @Override
          public void run() {
            umc.m1();
          }
        }, "t1");
        Thread t2 = new Thread(new Runnable() {
          @Override
          public void run() {
            umc.m2();
          }
        }, "t2");
        Thread t3 = new Thread(new Runnable() {
          @Override
          public void run() {
            umc.m3();
          }
        }, "t3");
        Thread t4 = new Thread(new Runnable() {
          @Override
          public void run() {
            umc.m4();
          }
        }, "t4");
        Thread t5 = new Thread(new Runnable() {
          @Override
          public void run() {
            umc.m5();
          }
        }, "t5");
    
        t1.start(); // c1
        t2.start(); // c1
        t3.start(); // c2
    
        try {
          Thread.sleep(2000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
    
        t4.start(); // c1 signalAll
        try {
          Thread.sleep(2000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        t5.start(); // c2
      }
    }

支持重入:

    public class TestReentrant {
    
      private ReentrantLock lock = new ReentrantLock();
    
      public void m1() {
        try {
          lock.lock();
          System.out.println("进入m1方法");
          // 调用m2方法
          m2();
    
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          lock.unlock();
        }
      }
    
      public void m2() {
        try {
          lock.lock();
          System.out.println("进入m2方法");
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          lock.unlock();
        }
      }
    
      public static void main(String[] args) {
        TestReentrant thc = new TestReentrant();
        thc.m1();
      }
    }

二、读写锁

ReentrantReadWriteLock,其核心就是实现读写分离的锁。在高并发访问下,尤其时读多写少的情况下,性能要远高于重入锁。synchronized、ReentrantLock,同一时间内,只能有一个线程进行访问被锁定的代码,那么读写锁则不同,其本质时分成两个锁,即读锁、写锁。在读锁下,多个线程可以并发的进行访问,但是在写锁的时候,只能一个一个的顺序访问。

    public class UseReentrantReadWriteLock {
    
      private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
      private ReadLock readLock = rwLock.readLock();
      private WriteLock writeLock = rwLock.writeLock();
    
      public void read() {
        try {
          readLock.lock();
          System.out.println("当前线程:" + Thread.currentThread().getName() + "进入...");
          Thread.sleep(3000);
          System.out.println("当前线程:" + Thread.currentThread().getName() + "退出...");
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          readLock.unlock();
        }
      }
    
      public void write() {
        try {
          writeLock.lock();
          System.out.println("当前线程:" + Thread.currentThread().getName() + "进入...");
          Thread.sleep(3000);
          System.out.println("当前线程:" + Thread.currentThread().getName() + "退出...");
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          writeLock.unlock();
        }
      }
    
      public static void main(String[] args) {
    
        final UseReentrantReadWriteLock urrw = new UseReentrantReadWriteLock();
    
        Thread t1 = new Thread(() -> {
          urrw.read();
        }, "t1");
        Thread t2 = new Thread(() -> {
          urrw.read();
        }, "t2");
        Thread t3 = new Thread(() -> {
          urrw.write();
        }, "t3");
        Thread t4 = new Thread(() -> {
          urrw.write();
        }, "t4");
    
        // t1.start(); // R
        // t2.start(); // R
    
        t1.start(); // R
        t3.start(); // W
    
        // t3.start();// W
        // t4.start();// W
    
      }
    }

三、乐观锁

总是认为不会产生并发问题,每次去取数据的时候总认为不会有其他线程对数据进行修改,因此不会上锁,但是在更新时会判断其他线程在这之前有没有对数据进行修改,一般会使用版本号机制或CAS操作实现。

version方式:一般是在数据表中加上一个数据版本号version字段,表示数据被修改的次数,当数据被修改时,version值会加一。当线程A要更新数据值时,在读取数据的同时也会读取version值,在提交更新时,若刚才读取到的version值为当前数据库中的version值相等时才更新,否则重试更新操作,直到更新成功。

核心SQL语句

update table set x=x+1, version=version+1 where id=#{id} and version=#{version};

CAS操作方式:即compare and swap 或者 compare and set,涉及到三个操作数,数据所在的内存值,预期值,新值。当需要更新时,判断当前内存值与之前取到的值是否相等,若相等,则用新值更新,若失败则重试,一般情况下是一个自旋操作,即不断的重试。

四、悲观锁

总是假设最坏的情况,每次取数据时都认为其他线程会修改,所以都会加锁(读锁、写锁、行锁等),当其他线程想要访问数据时,都需要阻塞挂起。可以依靠数据库实现,如行锁、读锁和写锁等,都是在操作之前加锁,在Java中,synchronized的思想也是悲观锁。