yield(放弃、谦逊、礼让)

两个线程抢占CPU各自执行任务,代码如下:

public class Demo03 {

	public static void main(String[] args) throws InterruptedException {
		new Thread(new Runnable() {
			@Override
			public void run() {
				while(true){
					System.out.println(Thread.currentThread().getName()+" -> ");
				}
			}
		},"t1线程").start();
		new Thread(new Runnable() {
			@Override
			public void run() {
				while(true){
					System.out.println(Thread.currentThread().getName()+" -> ");
				}
			}
		},"t2线程").start();
	}

}

  运行如图:

这个时候,t1抢到了立马快速执行,t2抢到也快速执行。

引入yield()

在JDK文档中,

yield public static void yield() 

是被定义为static的

t1,t2都使用yield方法暂时放弃争夺CPU使用权

运行结果如图:

这时候会产生,严格说是会有轮流交替执行的情况。

原文地址:https://www.cnblogs.com/mengxinrenyu/p/8274408.html