- 让当前正在执行的线程进入暂停状态,但不阻塞
- 将线程从运行状态转为就绪状态
- 让CPU重新调度,礼让但不一定成功!
package com.example.demo.thread;
/**
* @projectName: demo
* @package: com.example.demo.thread
* @className: TestYiedld
* @author:
* @description: 测试两个线程
* @date: 2021/11/26 18:25
*/
public class TestYiedld {
public static void main(String[] args) {
MyYield myYield1 = new MyYield();
MyYield myYield2 = new MyYield();
new Thread(myYield1,"线程1").start();
new Thread(myYield2,"线程2").start();
}
}
class MyYield implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"线程启动!");
Thread.yield();
System.out.println(Thread.currentThread().getName()+"线程停止!");
}
}
去掉Thread.yield();
一定是下面的结果

礼让成功的结果(资源礼让后cpu分给1)

礼让成功的结果(资源礼让后cpu分给2)

礼让不成功的结果

网友评论