Thread yield()方法的使用:
yield这个单词有谦让的意思,那么这个方法也是一样的,一个线程yield之后,它会将占有的cpu资源让出来,再和其他线程一起去抢cpu资源,抢到cup使用权的还是有可能是原本的线程。
/*
@author Nian
@Date 2022/8/8 17:54
@purpose
@Note yield() is a static method.A thread if yield,other thread not always can rob the cpu resource
*/
public class YieldTest {
public static void main(String[] args) {
Thread thread1 = new Thread(()->{
for (int i = 0; i < 100; i++) {
if(i == 10){
Thread.yield();
}
System.out.println(Thread.currentThread().getName()+" "+i);
}
},"Thread1");
Thread thread2 = new Thread("Thread2"){
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName()+ " is printing " +i);
}
}
};
thread1.start();
thread2.start();
}
}