Reputation: 109
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
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
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:
notifyAll()
(or notify) on the same object lock
is referencing, exit this method normally..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