1. The two methods belong to different, sleep belongs to the thread class. The wait () method, then, belongs to the object class.
The 2.sleep method causes the thread to suspend execution of the set time, losing control of the CPU but his monitor state still exists, and the specified time has passed before he can begin execution again.
The 3sleep method does not release the object lock but the wait () method releases the object lock
The 4.wait () method must be in a locked state before it can be used or it will error java.lang.IllegalMonitorStateException, and the sleep method can be used at any time. The sleep method needs to catch exception information, and wait and his matching notifyall,notify do not need to be captured.
5. Here we want to understand the concept of the lower critical section: Sometimes you just want to prevent multiple threads from simultaneously accessing part of the code inside the method, rather than preventing access to the entire method, in this way the separated code snippet is called the critical section she also uses the Synchronized keyword to establish, here
Synchronized is used to specify an object in which a lock is used to specify that the lock of an object is used to synchronize the code in curly braces
Synchronized (SyncObject) {
This code can is accessed by only one task in a time
}
This is also known as a synchronous control block. Before entering this code, you must get a lock on the SyncObject object, and if the other thread has already got the lock, wait for the lock to be released before entering the critical section. By using synchronous control blocks instead of synchronizing the entire method, you can make a significant increase in the time and performance of multiple tasks accessing objects.
6. Someone asked why there was a sleep method and wait. You might say that wait is able to pause the thread and await a notification to wake it up, but I can say that sleep can do it, that is, interrupt () at sleep and then perform what you want to do in the catch of an exception catch. The big difference here is why you use wait because there may be a few threads vying for the code that executes the critical section, but if there is a condition in the critical section that makes it necessary to release the lock, then use a wait and wake with Notiy.