Similarities and differences between thread. Sleep (long) and object. Wait (long) (zz )-

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.