How can I measure thread waiting time?

后端 未结 3 1087
面向向阳花
面向向阳花 2021-01-19 08:14

I couldn\'t find out how to measure the time that a Thread is waiting locked. I have to determine if a Thread is waiting locked more than 1 second and if so to run another T

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-19 09:05

    Time it using Sytem.nanoTime(); just before and after the wait.

    long start = System.nanoTime();
    wait();
    long time = System.nanoTime() - start; // nanos
    

    Or:

    long start = System.nanoTime();
    synchronized (objHere)
    {
        long time = System.nanoTime() - start; // nanos
        // ...
    }
    

    Note: If a Thread is locked, the scheduler will continue with other Threads. You don't have to do this manually. That is the idea of threads. Maybe you are facing a deadlock? Wikipedia says it nicely:

    A deadlock is a situation in which two or more competing actions are each waiting for the other to finish, and thus neither ever does.

提交回复
热议问题