This is the 13th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

CPU time chips are allocated only when running is enabled. The CPU allocates time for each thread to execute. Each time slice is very short, and the CPU keeps switching between different threads. If the lock is held, the execution fragment is executed synchronously, and if the lock is released, other threads are allowed to continue executing the block. \

Thread.sleep(long) is a static call to the Thread class.

Sleep is a thread method, which has nothing to do with the lock. It releases CPU resources, but does not release the lock. If the thread enters sleep, it releases CPU resources, and if the outer package has Synchronize, the lock is not released.

Wait () and notify() and notifyAll() are java.lang.object methods.

All of these methods are used to coordinate multiple threads’ access to shared data, so they must be used within a Synchronized block. How can you give others access to shared data while the current thread is still in the Synchronized block? These three methods are needed for flexible control. Wait is used in the locking mechanism to release the lock. 1) Wait () causes the current thread to suspend execution and release the object lock flag, allowing other threads to enter the Sychronized data block. The current thread is placed in the object wait pool. 2) When notify() is called, an arbitrary thread is removed from the wait pool of the object and placed in the lock flag wait pool. Only threads in the lock flag wait pool can obtain the lock flag; Notify () does not work if there are no threads in the lock flag wait pool. NotifyAll () removes all waiting threads from the object wait pool and puts them into the lock flag wait pool.

Join () is called by thread objects.

Wait for the thread to terminate, that is, the main thread waits for the child thread to terminate, that is, the code after the child thread calls the join () method, until the child thread ends. If the thread aThread calls the bThread.join () method, it is aThread that blocks until the bThread completes.





Four,

There are many resources for threads, but they should include CPU resources and lock resources. Sleep frees CPU resources, but does not release lock resources. Wait frees CPU resources and locks resources. \

image.png