仰望星空_Star 2019-04-16 23:32 采纳率: 0%
浏览 1562

ReentrantLock tryLock(timeout,timeUnit) 超时未返回

以下代码中,tryLock(timeout,timeUnit) 方法在超过2s后并未输出 “T2 got no lock end” 而是在T1线程结束后才有输出,但是如果以debug 模式运行或者替换代码中的Math.random()为其他耗时操作比如"TimeUnit.SECONDS.sleep(1)"时却可以在2s后输出 "T2 got no lock end",请问为什么会这样?

public class MyService2 {
public ReentrantLock lock = new ReentrantLock();

public void waitMethod() {
    try {
        System.out.println(System.currentTimeMillis() + " " + Thread.currentThread().getName() + " enter ");
        boolean b = lock.tryLock(2, TimeUnit.SECONDS);
        if (b) {
            System.out.println(System.currentTimeMillis() + " lock begin:" + Thread.currentThread().getName());
            for (int i = 0; i < Integer.MAX_VALUE / 10; i++) {
                Math.random();
            }
            System.out.println(System.currentTimeMillis() + " lock end " + Thread.currentThread().getName());
            return;
        }
        System.out.println(System.currentTimeMillis() + " " + Thread.currentThread().getName() + " got no lock end ");
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        if (lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }
}

public static void main(String[] args) throws InterruptedException {
    MyService2 myService2 = new MyService2();
    Runnable runnable = myService2::waitMethod;
    Thread thread1 = new Thread(runnable);
    thread1.setName("T1");
    thread1.start();
    TimeUnit.MILLISECONDS.sleep(10);
    Thread thread2 = new Thread(runnable);
    thread2.setName("T2");
    thread2.start();
}
  • 写回答

1条回答 默认 最新

  • ꧁gaoKuo꧂ 2019-04-17 09:21
    关注

    这个太像虚拟机优化的现象了

    for (int i = 0; i < Integer.MAX_VALUE / 10; i++) {
                    Math.random();
                }
    

    这段代码应该是没有运行的,如果你换成

    for (int i = 0; i < 100000; i++) {
                    System.out.println(Math.random());
                }
    

    结果应该会像你想的那样,这样会对外界产生影响

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!