仰望星空_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());
                }
    

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

    评论

报告相同问题?

悬赏问题

  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch