Victor
Victor

Reputation: 109

Java Object.wait(long) how does it wake up itself?

example:

public static void main(String[] args) throws InterruptedException {
    synchronized (lock) {
        for (; ; ) {
            System.out.println("每5秒打印一次");
            lock.wait(5000);
        }
    }
}

Just a single-thread loop waits for a few seconds and wakes up to print information, no other threads call notify, how does it automatically wake up itself?

Upvotes: 0

Views: 239

Answers (2)

something
something

Reputation: 174

There's a scheduler whose job it is to run threads. The scheduler knows about threads and whether they are currently runnable. It presumably has a queue of objects waiting on timer expiration. Those threads are not runnable 'now' but they become runnable when their time is up.

This is the same principle as in most operating systems. Execute a 'sleep for N seconds' system call. Something exists that will make the thread runnable again.

Upvotes: 1

rzwitserloot
rzwitserloot

Reputation: 103678

What did you think the 5000 means there?

lock.wait(5000) means: Start a timer and wait until the first of any of these 3 things occurs:

  • If 5000 milliseconds (5 seconds) pass, exit this method normally.
  • If someone calls notifyAll() (or notify) on the same object lock is referencing, exit this method normally.
  • If someone calls .interrupt() on this thread, exit by way of throwing InterruptedException.

So, if nobody is invoking notify, then this will wait 5 seconds. It's just a silly way of writing Thread.sleep(5000).

Upvotes: 2

Related Questions