SoFunction
Updated on 2025-03-03

The difference between sleep method and yield method of thread in java

1. sleep() method

1.1 Definition of sleep() method

sleep()The method isThreadA static method of the class, used to make the current thread enter a sleep state (blocking state) for a specified period of time. During this time, the thread will pause execution and give up CPU resources to other threads. After the sleep time is over, the thread will automatically return from the sleep state to the runnable state (Runnable), waiting for the operating system to reschedule.

sleep()There are two overloaded versions of the method:

public static void sleep(long millis) throws InterruptedException;
public static void sleep(long millis, int nanos) throws InterruptedException;
  • The first method causes the thread to sleep as specified as milliseconds.
  • The second method causes the thread to sleep with the specified number of milliseconds and the additional number of nanoseconds.

1.2 How the sleep() method works

When the thread calls()When the current thread will enter a blocking state, freeing CPU resources, and other threads can use this time slice to execute.sleep()Methods do not release locks or monitors, i.e. if threads are called within synchronous blocks or methodssleep(), it still holds the lock.

sleep()Methods can be thrownInterruptedException, which means that if the thread is interrupted during sleep,sleep()This exception will be thrown. Therefore, callsleep()This exception is usually required.

1.3 Application scenarios of sleep() method

  • Speed ​​limit operation: When it is necessary to control the execution frequency of certain operations, it can be usedsleep()method. For example, control the frame rate in a game loop, or limit the frequency of sending a request in a network request.
  • Waiting for conditions: In some scenarios, threads may need to wait for a period of time before rechecking a certain condition. This can be usedsleep()To achieve it.
  • Analog delaysleep()It can be used to simulate the execution delay of tasks to better simulate the real execution environment during testing and debugging.

1.4 Example of sleep() method

public class SleepExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            ("Thread is going to sleep...");
            try {
                (2000);  // Thread sleeps for 2 seconds            } catch (InterruptedException e) {
                ();
            }
            ("Thread is awake!");
        });

        ();
    }
}

In this example, the thread enters sleep state for 2 seconds after startup, and then continues to execute the remaining code.

2. The yield() method

2.1 Definition of yield() method

yield()The method isThreadAnother static method of the class is used to prompt the thread scheduler to prompt the current thread to give up CPU resources so that other threads with the same priority or higher priority can obtain execution opportunities.yield()The call of a method does not guarantee that the current thread will give up the CPU resources immediately, nor does it guarantee that other threads will get execution opportunities. This depends entirely on the implementation of the thread scheduler and the current system load.

public static native void yield();

2.2 How the yield() method works

When the thread calls()When the thread scheduler checks whether other threads with the same priority or higher priority are in the runnable state (Runnable). If there is, they will get execution opportunities; if not, the current thread may continue to run. therefore,yield()What works is similar to telling the scheduler: "I have done some work now, and you can choose to let other threads execute."

yield()The method does not block the thread, the thread simply enters the Runnable from the "running state" to give other threads a chance to run.

2.3 Application scenarios of yield() method

  • Debugging and testing: When debugging and testing multithreaded applications,yield()Can help simulate and verify thread scheduling behavior.
  • Reduce competition: In some scenarios with higher competition conditions,yield()It can be used to prompt the thread scheduler to switch to other threads to mitigate competition among threads.
  • Collaborative multitasking: Although modern operating systems mostly use preemptive scheduling, in some cases,yield()It can help achieve a collaborative scheduling-like effect, especially in multithreaded compute-intensive tasks.

2.4 Example of yield() method

public class YieldExample {
    public static void main(String[] args) {
        Runnable task1 = () -> {
            for (int i = 0; i < 5; i++) {
                ("Task 1 - " + i);
                ();  // Prompt the scheduler to give up the CPU            }
        };

        Runnable task2 = () -> {
            for (int i = 0; i < 5; i++) {
                ("Task 2 - " + i);
                ();  // Prompt the scheduler to give up the CPU            }
        };

        Thread thread1 = new Thread(task1);
        Thread thread2 = new Thread(task2);

        ();
        ();
    }
}

In this example, two threads run alternately, each thread is called after completing a loopyield(), prompts the scheduler to allocate CPU time to other threads.

3. The difference between sleep() and yield()

3.1 Different purposes

  • sleep()sleep()The main purpose is to put the thread into a dormant state for a period of time, thereby pausing execution and freeing CPU resources. During this time, threads do not compete and consume CPU resources until the sleep time ends or is interrupted.

  • yield()yield()The purpose is to prompt the thread scheduler to prompt the current thread to give up CPU resources, so that other threads with the same priority or higher priority have the opportunity to execute.yield()There is no guarantee that the current thread will be suspended, it just indicates that the current thread is willing to give up the CPU time slice briefly.

3.2 Different behaviors

  • sleep()sleep()It is clear time control, and the thread is callingsleep()The specified time will be hibernated. During this time, the thread will not perform any operations, and the thread must wait for the time to end before it can continue to execute.

  • yield()yield()There is no time control, it just switches the current thread from "running state" to "runable state". It does not necessarily cause the thread to give up the CPU time slice, the scheduler may allow the current thread to continue running, or it may select another thread.

3.3 Impact on thread state

  • sleep(): Calledsleep()Will cause the thread to enter a "blocked state" until the specified time arrives or is interrupted.

  • yield(): Calledyield()The thread will not enter the blocking state, the thread is still in the "runnable state", just waiting for the scheduler to reschedule.

3.4 Whether to release the lock

  • sleep()sleep()No locks held by the thread will be released, even if the thread is called within the synchronous blocksleep(), the lock will still be held and other threads cannot acquire the lock.

  • yield()yield()The lock will not be released. The thread is callingyield()All locks are still held, which means that even if the thread briefly gives up the CPU, other threads cannot enter the synchronization block held by the thread.

3.5 Exception thrown

  • sleep()sleep()May be thrownInterruptedException, If the thread is interrupted by other threads during sleep, this exception must be handled.

  • yield()yield()Will not be thrownInterruptedExceptionor any other exception.

3.6 Actual use effect

  • sleep(): Applicable to scenarios where execution needs to be clearly suspended, such as speed limits, waiting conditions, etc.sleep()Make sure that the thread does not perform any tasks within the specified time and gives up CPU resources.

  • yield(): Suitable for scenarios where you want the scheduler to consider switching to other threads for execution.yield()The effect depends on the implementation of the thread scheduler and is not guaranteed to switch to other threads.

4. Summary of application scenarios of sleep() and yield()

4.1 Application scenarios of sleep()

  • Implement timing tasks: In a scheduled task,sleep()It can be used to make the thread wait for a specified time and then continue to execute the task.
  • Speed ​​limit processing: In scenarios such as network request and data processing,sleep()It can be used to control the execution frequency and prevent system overload.
  • Analog delay: In the test,sleep()Can be used to simulate tasks

delay execution in order to verify the behavior of the program.

4.2 Application scenarios of yield()

  • Debugging and testingyield()It can help debug multithreaded programs and check thread scheduling behavior, especially when race conditions are high.
  • Reduce competition: In high competition scenarios,yield()The scheduler can be prompted to switch to other threads, thereby reducing the intensity of resource competition.
  • Optimize concurrency performance: In some computing-intensive tasks,yield()It can help achieve fairer scheduling and avoid some threads from consuming CPU for a long time.

5. Conclusion

sleep()andyield()They are two important methods in Java multi-threaded programming. Although they can both control the execution order and time of threads, their roles and application scenarios are significantly different.sleep()Used for clear time control, letting threads go to sleep and giving up CPU resources;yield()Used to prompt the scheduler that the current thread is willing to give up the CPU, but it is not guaranteed to give up.

In actual development, use it reasonablysleep()andyield(), can effectively control the execution order of threads, optimize the performance of concurrent programs, and avoid unnecessary resource competition.

This is the end of this article about the difference between the sleep() method and the yield() method of threads in java. For more related java sleep() and yield() content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!