浅谈Java中的锁:Synchronized、重入锁、读写锁

矫情吗;* 2022-02-15 14:38 286阅读 0赞

Synchronized

首先我们来看一段简单的代码:

  1. public class NotSyncDemo {
  2. public static int i=0;
  3. static class ThreadDemo extends Thread {
  4. @Override
  5. public void run() {
  6. for (int j=0;j<10000;j++){
  7. i++;
  8. }
  9. }
  10. }
  11. public static void main(String[] args) throws InterruptedException {
  12. ThreadDemo t1=new ThreadDemo();
  13. ThreadDemo t2=new ThreadDemo();
  14. t1.start();t2.start();
  15. t1.join();
  16. t2.join();
  17. System.out.println(i);
  18. }
  19. }

上方的代码使用了2个线程同时对静态变量i进行++操作,理想中的结果最后输出的i的值应该是20000才对,但是如果你执行这段代码的时候你会发现最后的结果始终是一个比20000小的数。这个就是由于JMM规定线程操作变量的时候只能先从主内存读取到工作内存,操作完毕后在写到主内存。而当多个线程并发操作一个变量时很可能就会有一个线程读取到另外一个线程还没有写到主内存的值从而引起上方的现象。
想要避免这种多线程并发操作引起的数据异常问题一个简单的解决方案就是加锁。JDK提供的synchronize就是一个很好的选择。
synchronize的作用就是实现线程间的同步,使用它加锁的代码同一时刻只能有一个线程访问,既然是单线程访问那么就肯定不存在并发操作了。
synchronize可以有多种用法,下面给出各个用法的示例代码。
Synchronized的三种使用方式
给指定对象加锁,进入代码前需要获得对象的锁

  1. public class SyncObjDemo {
  2. public static Object obj = new Object();
  3. public static int i = 0;
  4. static class ThreadDemo extends Thread {
  5. @Override
  6. public void run() {
  7. for (int j = 0; j < 10000; j++) {
  8. synchronized (obj) {
  9. i++;
  10. }
  11. }
  12. }
  13. }
  14. public static void main(String[] args) throws InterruptedException {
  15. ThreadDemo t1 = new ThreadDemo();
  16. ThreadDemo t2 = new ThreadDemo();
  17. t1.start();
  18. t2.start();
  19. t1.join();
  20. t2.join();
  21. System.out.println(i);
  22. }
  23. }

给方法加锁,相当于给当前实例加锁,进入代码前需要获得当前实例的锁

  1. public class SyncMethodDemo {
  2. public static int i = 0;
  3. static class ThreadDemo extends Thread {
  4. @Override
  5. public void run() {
  6. for (int j = 0; j < 10000; j++) {
  7. add();
  8. }
  9. }
  10. public synchronized void add(){
  11. i++;
  12. }
  13. }
  14. public static void main(String[] args) throws InterruptedException {
  15. ThreadDemo threadDemo=new ThreadDemo();
  16. Thread t1 = new Thread(threadDemo);
  17. Thread t2 = new Thread(threadDemo);
  18. t1.start();
  19. t2.start();
  20. t1.join();
  21. t2.join();
  22. System.out.println(i);
  23. }
  24. }

给静态方法加锁,相当于给当前类加锁,进入代码前需要获得当前类的锁。这种方式请慎用,都锁住整个类了,那效率能高哪去

  1. public static synchronized void add(){
  2. i++;
  3. }

重入锁
在JDK6还没有优化synchronize之前还有一个锁比它表现的更为亮眼,这个锁就是重入锁。
我们来看一下一个简单的使用重入锁的案例:

  1. public class ReentrantLockDemo {
  2. public static ReentrantLock lock = new ReentrantLock();
  3. public static int i = 0;
  4. static class ThreadDemo extends Thread {
  5. @Override
  6. public void run() {
  7. for (int j = 0; j < 10000; j++) {
  8. lock.lock();
  9. try {
  10. i++;
  11. }finally {
  12. lock.unlock();
  13. }
  14. }
  15. }
  16. }
  17. public static void main(String[] args) throws InterruptedException {
  18. ThreadDemo t1 = new ThreadDemo();
  19. ThreadDemo t2 = new ThreadDemo();
  20. t1.start();
  21. t2.start();
  22. t1.join();
  23. t2.join();
  24. System.out.println(i);
  25. }
  26. }

上方代码使用重入锁同样实现了synchronize的功能。并且呢,我们可以看到使用冲入锁是显示的指定什么时候加锁什么时候释放的,这样对于一些流程控制就会更加的有优势。

再来看这个锁为什么叫做重入锁呢,这是因为这种锁是可以反复进入的,比如说如下操作是允许的。

  1. lock.lock();
  2. lock.lock();
  3. try {
  4. i++;
  5. }finally {
  6. lock.unlock();
  7. lock.unlock();
  8. }

不过需要注意的是如果多次加锁的话同样也要记得多次释放,否则资源是不能被其他线程使用的。
在之前的文章:多线程基本概念 中有提到过因为线程优先级而导致的饥饿问题,重入锁提供了一种公平锁的功能,可以忽略线程的优先级,让所有线程公平竞争。使用公平锁的方式只需要在重入锁的构造方法传入一个true就可以了。

  1. public static ReentrantLock lock = new ReentrantLock(true);

重入锁还提供了一些高级功能,例如中断。
对于synchronize来说,如果一个线程获取资源的时候要么阻塞要么就是获取到资源,这样的情况是无法解决死锁问题的。而重入锁则可以响应中断,通过放弃资源而解决死锁问题。
使用中断的时候只需要把原先的lock.lock()改成lock.lockInterruptibly()就OK了。
来看代码示例:

  1. public class ReentrantLockInterruptDemo {
  2. public static ReentrantLock lock1 = new ReentrantLock();
  3. public static ReentrantLock lock2 = new ReentrantLock();
  4. static class ThreadDemo extends Thread {
  5. int i = 0;
  6. public ThreadDemo(int i) {
  7. this.i = i;
  8. }
  9. @Override
  10. public void run() {
  11. try {
  12. if (i == 1) {
  13. lock1.lockInterruptibly();
  14. try {
  15. Thread.sleep(1000);
  16. } catch (InterruptedException e) {
  17. e.printStackTrace();
  18. }
  19. lock2.lockInterruptibly();
  20. } else {
  21. lock2.lockInterruptibly();
  22. try {
  23. Thread.sleep(1000);
  24. } catch (InterruptedException e) {
  25. e.printStackTrace();
  26. }
  27. lock1.lockInterruptibly();
  28. }
  29. System.out.println(Thread.currentThread().getName() + "完成任务");
  30. } catch (InterruptedException e) {
  31. e.printStackTrace();
  32. } finally {
  33. if (lock1.isHeldByCurrentThread()) {
  34. lock1.unlock();
  35. }
  36. if (lock2.isHeldByCurrentThread()) {
  37. lock2.unlock();
  38. }
  39. System.out.println(Thread.currentThread().getName() + "退出");
  40. }
  41. }
  42. }
  43. public static void main(String[] args) throws InterruptedException {
  44. Thread t1 = new Thread(new ThreadDemo(1),"t1");
  45. Thread t2 = new Thread(new ThreadDemo(2),"t2");
  46. t1.start();
  47. t2.start();
  48. Thread.sleep(1500);
  49. t1.interrupt();
  50. }
  51. }

查看上方代码我们可以看到,线程t1启动后先占有lock1,然后会在睡眠1秒之后试图占有lock2,而t2则先占有lock2,然后试图占有lock1。这个过程则势必会发生死锁。而如果再这个时候我们给t1一个中断的信号t1就会响应中断从而放弃资源,继而解决死锁问题。
除了提供中断解决死锁以外,重入锁还提供了限时等待功能来解决这个问题。
限时等待的使用方式是使用lock.tryLock(2,TimeUnit.SECONDS)
这个方法有两个参数,前面是等待时长,后面是等待时长的计时单位,如果在等待时长范围内获取到了锁就会返回true。
请看代码示例:

  1. public class ReentrantLockTimeDemo {
  2. public static ReentrantLock lock = new ReentrantLock();
  3. static class ThreadDemo extends Thread {
  4. @Override
  5. public void run() {
  6. try {
  7. if (lock.tryLock(2, TimeUnit.SECONDS)) {
  8. try {
  9. System.out.println(Thread.currentThread().getName() + "获取锁成功");
  10. Thread.sleep(3000);
  11. } catch (InterruptedException e) {
  12. e.printStackTrace();
  13. }
  14. } else {
  15. System.out.println(Thread.currentThread().getName() + "获取锁失败");
  16. }
  17. } catch (InterruptedException e) {
  18. e.printStackTrace();
  19. } finally {
  20. if (lock.isHeldByCurrentThread()) {
  21. lock.unlock();
  22. }
  23. }
  24. }
  25. }
  26. public static void main(String[] args) throws InterruptedException {
  27. Thread t1 = new Thread(new ThreadDemo(), "t1");
  28. Thread t2 = new Thread(new ThreadDemo(), "t2");
  29. t1.start();
  30. t2.start();
  31. }
  32. }

同样的tryLock也可以不带参数,不带参数的时候就是表示立即获取,获取不成功就直接返回false
我们知道synchronize配合wait和notify可以实现等待通知的功能,重入锁同样也提供了这种功能的实现。那就是condition。使用lock.newCondition()就可以获得一个Condition对象。
下面请看使用Condition的代码示例:

  1. public class ReentrantLockWaitNotifyThread {
  2. public static ReentrantLock lock = new ReentrantLock();
  3. public static Condition condition = lock.newCondition();
  4. static class WaitThreadDemo extends Thread {
  5. @Override
  6. public void run() {
  7. try {
  8. System.out.println("WaitThread wait,time=" + System.currentTimeMillis());
  9. lock.lock();
  10. condition.await();
  11. } catch (InterruptedException e) {
  12. e.printStackTrace();
  13. }finally {
  14. lock.unlock();
  15. System.out.println("WaitThread end,time=" + System.currentTimeMillis());
  16. }
  17. }
  18. }
  19. static class NotifyThreadDemo extends Thread {
  20. @Override
  21. public void run() {
  22. lock.lock();
  23. System.out.println("NotifyThread notify,time=" + System.currentTimeMillis());
  24. condition.signal();
  25. try {
  26. Thread.sleep(2000);
  27. } catch (InterruptedException e) {
  28. e.printStackTrace();
  29. }finally {
  30. lock.unlock();
  31. System.out.println("NotifyThread end,time=" + System.currentTimeMillis());
  32. }
  33. }
  34. }
  35. public static void main(String[] args) {
  36. WaitThreadDemo waitThreadDemo = new WaitThreadDemo();
  37. NotifyThreadDemo notifyThreadDemo = new NotifyThreadDemo();
  38. waitThreadDemo.start();
  39. try {
  40. Thread.sleep(100);
  41. } catch (InterruptedException e) {
  42. e.printStackTrace();
  43. }
  44. notifyThreadDemo.start();
  45. }
  46. }

读写锁
通过上方的内容我们知道了为了解决线程安全问题,JDK提供了相当多的锁来帮助我们。但是如果多线程并发读的情况下是不会出现线程安全问题的,那么有没有一种锁可以在读的时候不控制,读写冲突的时候才会控制呢。答案是有的,JDK提供了读写分离锁来实现读写分离的功能。
这里给出使用读写锁的一个代码示例

  1. public class ReadWriteLockDemo {
  2. public static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
  3. public static Lock readLock = readWriteLock.readLock();
  4. public static Lock writeLock = readWriteLock.writeLock();
  5. public static void read(Lock lock) {
  6. lock.lock();
  7. try {
  8. System.out.println("readTime:" + System.currentTimeMillis());
  9. Thread.sleep(2000);
  10. } catch (InterruptedException e) {
  11. e.printStackTrace();
  12. } finally {
  13. lock.unlock();
  14. }
  15. }
  16. public static void write(Lock lock) {
  17. lock.lock();
  18. try {
  19. System.err.println("writeTime:" + System.currentTimeMillis());
  20. Thread.sleep(2000);
  21. } catch (InterruptedException e) {
  22. e.printStackTrace();
  23. } finally {
  24. lock.unlock();
  25. }
  26. }
  27. static class ReadThread extends Thread {
  28. @Override
  29. public void run() {
  30. read(readLock);
  31. }
  32. }
  33. static class WriteThread extends Thread {
  34. @Override
  35. public void run() {
  36. write(writeLock);
  37. }
  38. }
  39. public static void main(String[] args) throws InterruptedException {
  40. for (int i = 0; i < 10; i++) {
  41. new ReadThread().start();
  42. }
  43. new WriteThread().start();
  44. new WriteThread().start();
  45. new WriteThread().start();
  46. }
  47. }

上方代码模拟了10个线程并发读,3个线程并发写的状况,如果我们使用synchronize或者重入锁的时候我想上方最后的耗时应该是26秒多。但是如果你执行 一下上方的代码你就会发现仅仅只花费了6秒多。这就是读写锁的魅力。

加java高级架构师群获取Java工程化、高性能及分布式、高性能、深入浅出。高架构。
性能调优、Spring,MyBatis,Netty源码分析和大数据等多个知识点高级进阶干货的直播免费学习权限
都是大牛带飞 让你少走很多的弯路的 群号是: 798891710对了 小白勿进 最好是有开发经验

发表评论

表情:
评论列表 (有 0 条评论,286人围观)

还没有评论,来说两句吧...

相关阅读

    相关

       在java多线程中,我们知道可以用synchronize关键字来实现线程间的同步互斥工作,还有更加优秀的机制去实现同步互斥工作,Lock对象。重入锁和读写锁,他们具有比

    相关 Synchronize

    Synchronize锁重入 拥有锁重入的功能 就是在使用synchronize时,当一个线程得到了一个对象的锁之后 再次,请求该对象时,可以再次得到该对象的锁