The difference between sleep, yield, wait, join (Ali interview) The difference between sleep, yield, join, notify, wait, notifyAll

1. Both Thread.sleep(long) and Thread.yield() are static methods of the Thread class, and they are called in the way of Thread.sleep(long)/Thread.yield() when they are called.

   And join() is called by the thread object.

2. The three methods of wait(), notify(), notifyAll() are all methods of java.lang.Ojbect! 

They are all used to coordinate the access of multiple threads to shared data, so these three methods must be used within the Synchronized statement block. As mentioned earlier, the Synchronized keyword is used to protect shared data and prevent other threads from accessing shared data. However, the flow of the program is very inflexible. How can other threads have the opportunity to access the shared data when the current thread has not exited the Synchronized data block? At this time, use these three methods to flexibly control. 

The wait() method causes the current thread to suspend execution and release the object lock flag, so that other threads can enter the Synchronized data block, and the current thread is put into the object waiting pool.

When the notify() method is called, an arbitrary thread will be removed from the object's waiting pool and placed in the lock flag waiting pool. Only threads in the lock flag waiting pool can acquire the lock flag; if there is no lock flag waiting pool in the lock flag waiting pool thread, notify() does not work. 

notifyAll() removes all threads waiting for that object from the object waiting pool and puts them in the lock flag waiting pool. 

 

 

The difference between sleep and Wait: see the difference, mainly to see the operating mechanism of the CPU:

The difference between them mainly considers two points: 1. Whether the cpu continues to execute, and 2. whether the lock is released.

For these two points, first explain the meaning of whether the cpu continues to execute: the cpu divides time slices for each thread to execute, each time slice is very short, and the cpu keeps switching between different threads, so that they seem to be at the same time. effect of execution.

Next, explain the meaning of whether the lock is released: if the lock is occupied, then the execution code fragment is executed synchronously. If the lock is released, other threads are allowed to continue executing this code block. 

Understand the meaning of the above two points, start to analyze sleep and wait:

After a period of sleep, the thread is often executed immediately. It can be seen that the CPU has been allocating time slices for this thread. If the outer package has Synchronize, the lock is not released. Therefore, the sleep cpu continues to execute, and the lock is not released;

wait, generally used in locking mechanisms

(wait is used for the lock mechanism, sleep is not, this is why sleep does not release the lock, the reason wait releases the lock, sleep is a thread method, and has nothing to do with the lock, wait, notify, notifyall are used together, use on the locking mechanism),

The lock must be released, because notify does not immediately call up this thread, so the cpu will not allocate a time slice for it, that is to say, the wait thread enters the waiting pool, the cpu does not divide the time slice to it, and the lock is released Lose.

 

 

 

 

 




finally:


 

1.sleep: The method of the Thread class must take a time parameter. It will let the current thread sleep into a blocked state and release the CPU (Ali interview question Sleep releases the CPU, wait) , providing the opportunity for other threads to run without considering the priority, but if there is a synchronization lock, sleep will not release the lock, that is, other threads cannot acquire synchronization lock

 

2.yield: Give up CPU scheduling , methods of Thread class, similar to sleep, except that the user cannot specify how long to pause, and the yield() method can only allow threads of the same priority to have the opportunity to execute. yield() just makes the current thread return to the executable state, so the thread that executes yield() may be executed again immediately after entering the executable state . Calling the yield method is just a suggestion, telling the thread scheduler that my work is almost done, and other threads of the same priority can use the CPU, and there is no mechanism to guarantee adoption.

 

3.wait: The methods of the Object class (notify(), notifyAll() are also Object objects), which must be placed in the loop body and the synchronization code block. The thread executing this method will release the lock and enter the thread waiting pool to wait to be awakened again. (notify wakes up randomly, notifyAll wakes up all, and the thread ends automatically wakes up) that is put into the lock pool to compete for synchronization locks

 

4. join: a special wait, the current running thread calls the join method of another thread, the current thread enters the blocking state until the other thread finishes running and waits for the thread to terminate. Note that this method also needs to catch exceptions.

Wait for the thread that called the join method to end before continuing. Such as: t.join();//It is mainly used to wait for the end of the t thread. If there is no such sentence, the main will be executed, resulting in unpredictable results.

I wrote an example:

public class abc_test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub 
        
        Thread thread =new Thread(new joinDemo());
        thread.start();
        
        for(int i=0;i<20;i++){
            
            System.out.println( "Main thread "+i+" this execution!" );
            
            if(i>=2){
                
                try {
                     // The t1 thread is merged into the main thread, the main thread stops the execution process, and executes the t1 thread instead, and continues until the execution of t1 is completed; 
                    thread.join();
                }catch(InterruptedException e){
                    e.printStackTrace ();
                }
            }
        }
        
        
        

    }

}

class joinDemo implements Runnable{

    @Override
    public void run() {
        // TODO Auto-generated method stub
        
        for(int i=0;i<10;i++){
            
            System.out.println( "Thread 1's "+i+" execution" );
        }
        
    }
    
      
     
}

The result is:

The 0th execution of the main thread!
The first execution of the main thread!
The second execution of the main thread!
The 0th execution of thread 1
Thread 1 executes for the first time
Thread 1 executes for the second time
Thread 1 executes for the third time
Thread 1 executes for the 4th time
Thread 1 executes for the 5th time
Thread 1 executes for the 6th time
Thread 1 executes for the 7th time
Thread 1 executes for the 8th time
Thread 1 executes for the 9th time
The third execution of the main thread!
The 4th execution of the main thread!
The 5th execution of the main thread!
The 6th execution of the main thread!
   .....
The 19th execution of the main thread!


The state of the 
thread There are four states of the thread, any thread must be in one of these four states: 
1) Generated (New): The thread object has been generated, but it has not been started, so it cannot be executed. For example, after a thread object is generated by new, it is not called the start() function. 
2) Runnable: Every system that supports multithreading has a scheduler, which selects a thread from the thread pool and starts it. When a thread is in the executable state, it may be in the thread pool waiting for the scheduler to start it; it may also be executing. For example, after executing the start() method of a thread object, the thread is in an executable state, but it is obvious that the thread is not necessarily executing at this time. 
3) Dead: When a thread ends normally, it is in a dead state. For example, after a thread's run() function is executed, the thread enters the dead state. 
4) Blocked: When a thread is in a stalled state, the system scheduler ignores it and does not schedule it. When a stalled thread returns to the executable state, it may re-execute. For example, after calling the wait() function on a thread, the thread enters the stagnant state, and it can only return to the executable state twice after calling notify or notifyAll on the thread twice. 

Reference: Topic: What is the difference between sleep, wait, join, yield?

Reference: Detailed explanation of the difference between yield(), sleep(), wait() in java - memo notes

Reference: The difference between sleep, yield, wait, join

Reference: sleep, yield, join, notify, wait, notifyAll difference

Reference: The difference between thread sleep and object wait for a period of time

Reference: The usage and difference of sleep(), wait() and notify() and notifyAll(), yield(), join() and other methods in Java threads

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324598444&siteId=291194637