Difference
1. sleep() will cause the current thread to pause for the specified time, without consuming CPU time slices
2. yield() only affects the CPU A prompt from the scheduler. If the CPU scheduler does not ignore this prompt, it will cause the thread context to switch.
sleep() will block the thread briefly and release CPU resources within a given time.
If yield() takes effect, yield() will make it enter the RUNNABLE state from the RUNNING state
sleep() will almost 100% complete the sleep for a given time, but the yield() prompt may not guarantee
One thread calling sleep() and another thread calling interrupt() will catch the interrupt signal, but yield will not
Instance
package cn.hanquan.test; /* * sleep模拟倒计时,每一秒减一 */ public class Lambda { public static void main(String[] args) { // Labmda表达式 new Thread(() -> { for (int i = 0; i < 100; i++) { System.out.println(i); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } }
The above is the detailed content of What is the difference between yield() and sleep() in Java?. For more information, please follow other related articles on the PHP Chinese website!