wait方法遇到的报错

刚刚开通了一个公众号,会分享一些技术博客和自己觉得比较好的项目,同时会更新一些自己使用的工具和图书资料,后面会整理一些面试资料进行分享,觉得有兴趣的可以关注一下。
在这里插入图片描述

文章目录


背景

今天在修复sonarqube的时候,碰到一个需要将Thread.sleep修复为wait方法,然后碰到这么个报错。

java.lang.IllegalMonitorStateException: current thread is not owner
	at java.base/java.lang.Object.wait(Native Method)

代码

代码比较简单

private final static Object lock = new Object();

private final static Random rand = new SecureRandom();
public synchronized static String genNextKey() {
      long currentTimeMillis = System.currentTimeMillis();
      int count = 0;
      while (currentTimeMillis <= lastTimeMill) {
          try {
              lock.wait((10L + rand.nextInt(90)));
          } catch (InterruptedException e) {
              log.warn("IdGenerator time interrupt", e);
              Thread.currentThread().interrupt();
          }
          currentTimeMillis = System.currentTimeMillis();
          count ++;

          if (count >= MAX_COUNT ) {
              throw new RuntimeException("get ID failed");
          }
      }
      lastTimeMill = currentTimeMillis;
      return String.valueOf(currentTimeMillis).substring(1, 13);
  }

分析

《java编程思想》第四版一书中有写:线程操作的wait()、notify()、notifyAll()方法只能在同步控制方法或同步控制块内调用。如果在非同步控制方法或控制块里调用,程序能通过编译,但运行的时候,将得到 IllegalMonitorStateException 异常,并伴随着一些含糊信息,比如 ‘当前线程不是拥有者’。其实异常的含义是 调用wait()、notify()、notifyAll()的任务在调用这些方法前必须 ‘拥有’(获取)对象的锁。
那明显其实synchronized wait拿的锁就不是一个锁了,只需要将方法上的synchronized 改为代码块即可。

private final static Object lock = new Object();

private final static Random rand = new SecureRandom();
 public static String genNextKey() {
     synchronized (lock) {
         long currentTimeMillis = System.currentTimeMillis();
         int count = 0;
         while (currentTimeMillis <= lastTimeMill) {
             try {
                 lock.wait((10L + rand.nextInt(90)));
             } catch (InterruptedException e) {
                 log.warn("IdGenerator time interrupt", e);
                 Thread.currentThread().interrupt();
             }
             currentTimeMillis = System.currentTimeMillis();
             count ++;

             if (count >= MAX_COUNT ) {
                 throw new RuntimeException("get ID failed");
             }
         }
         lastTimeMill = currentTimeMillis;
         return String.valueOf(currentTimeMillis).substring(1, 13);
     }
 }

其实是很基本的一个问题,技术基本功不扎实,还需要努力!

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦幻D开始

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值