In common: they are all in a multi-threaded environment. They can block a specified number of milliseconds in a program call and return results.
Difference: thread. Sleep (long) can not be called under the synchronized block, and the use of thread. Sleep () will not lose the current thread's synchronization lock on any object (MONITOR );
Object. Wait (long) must be used in the synchronized block. After being called, the monitor of the object is lost. The advantage of this is that it does not affect other threads to operate the object.
Here is an example of Java. util. Timer.
Private void mainloop (){
While (true ){
....
Synchronized (Queue ){
.....
If (! Taskfired) // task hasn' t yet fired; wait
Queue. Wait (executiontime-currenttime );
}
}
The reason why queue. Wait () is used instead of thread. Sleep () is that the queue object lock is temporarily abandoned and other threads can be allowed to perform some synchronization operations. For example:
Private void sched (timertask task, long time, long period ){
Synchronized (Queue ){
...
Queue. Add (task );
}
}
However, as mentioned in the previous article, queue is used. the prerequisite for wait (long) is that the execution time of the sched () action is short. Otherwise, if it is long, the queue. wait () cannot wake up on time.