Home > Java > javaTutorial > What is the difference between yield() and sleep() in Java?

What is the difference between yield() and sleep() in Java?

王林
Release: 2023-05-07 21:55:06
forward
1589 people have browsed it

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();
}
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template