Java thread (thread) Case study the difference between sleep and wait

Source: Internet
Author: User
Last time, I gave a general overview and summary of Java thread. Of course, most of them are in theory. This time I will explain two common and confusing methods in thread and use the example Code ...

FDifferences

Sleep () methodSleep () causes the current thread to enter the stuck state (blocking the current thread), giving rise to the usage of the cup to prevent the current thread from occupying the CPU resources of the process independently, to leave some time for other threads to execute;
Sleep () is the static (static) method of the thread class; therefore, it cannot change the machine lock of the object. Therefore, when the sleep () method is called in a synchronized block, although the thread is sleeping, the machine lock of the object is released, and other threads cannot access this object (even if they are asleep, they hold the object lock ).
After the sleep () sleep period expires, the thread may not be executed immediately because other threads may be running and are not scheduled to stop execution unless the thread has a higher priority.
Wait () methodThe wait () method is a method in the object class. When a thread executes the wait () method, it enters a waiting pool related to the object and loses (releases) the machine lock of the object (the machine lock is temporarily lost, and the object lock needs to be returned after the wait (long timeout) Timeout time is reached); other threads can access it;
Wait () uses Y, yyalll, or the specified sleep time to wake up threads in the current waiting pool.
Wiat () must be placed in the synchronized block; otherwise, an "Java. Lang. illegalmonitorstateexception" exception will be thrown during the program runtime.

The greatest difference between sleep () and wait () is:
When sleep () is sleeping, the object lock remains occupied;
When wait () is sleeping, the object lock is released.
However, both wait () and sleep () can interrupt the pause state of the thread through the interrupt () method, so that the thread immediately throws interruptedexception (but this method is not recommended ).

FCode

View code

 /**  
* Difference between thread sleep and wait
* @ Author Dreamsea
* 2012-1-15
*/
Public Class Threadtest Implements Runnable {
Int Number = 10;

Public Void Firstmethod () Throws Exception {
Synchronized ( This ){
Number ++ = 100;
System. Out. println (number );
}
}

Public Void Secondmethod () Throws Exception {
Synchronized ( This ){
/**
* (Rest for 2 s, blocking threads)
* To verify that the machine lock of the current thread object is occupied,
* Whether other synchronous code blocks can be accessed
*/
Thread. Sleep (2000 );
// This. Wait (2000 );
Number * = 200;
}
}

@ Override
Public Void Run (){
Try {
Firstmethod ();
} Catch (Exception e ){
E. printstacktrace ();
}
}

Public Static Void Main (string [] ARGs) Throws Exception {
Threadtest = New Threadtest ();
Thread thread = New Thread (threadtest );
Thread. Start ();
Threadtest. secondmethod ();
}
}

use the sleep () method to output the result: [display output]
use the wait () method to output the result: [display output]
let's give a rough analysis of this code segment. In the main () method, instantiate threadtest and start this thread, then call a method (secondmethod () of the thread. Because the method is called in the main thread, the normal method secondmethod () is called ()) it will be executed first (but it is not the thread method of the object after the normal method is executed. During the normal method execution, the methods of this thread will also be executed. They are executed alternately, only normal methods in the main thread will be executed first), so the program runs secondmethod () First, while the secondmethod () code snippet contains the synchronized block, therefore, after the secondmethod method is executed, the method occupies the host lock of the object, causing the thread and method of the object to remain in the blocking status and cannot be executed until secondemethod releases the lock.
Use threa D. when the sleep (2000) method is used, other synchronization threads (secondmethod () of the object cannot be executed because sleep is blocking the thread and holding the lock of the object, the secondmethod () method can be executed until the synchronized block is executed (sleep is completed). Therefore, the output result is Number * 200 + 100.
use this. when the wait (2000) method is executed, the secondmethod () method also locks the machine lock of the object and runs it to this. wait (2000), the method will sleep for 2 seconds and release the lock currently held. At this time, the synchronization method of this thread will be executed (because the lock held by secondmethod has been wait () released), so the output result is: Number + 100;
[display process]
the difference between sleep () and wait () methods has been explained, if you are interested in the thread, I asked Nono: Add "system. out. P Rintln ("number =" + threadtest. Number); "to guess what results will be output... j

Related Article

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.