yield 礼让线程,让当前正在执行的线程暂停而不是阻塞线程 将线程从运行状态转入就绪状态 让cpu调度器重新调度
public class n {
public static void main(String[]args)
{
test t =new test();
new Thread(t,"a").start();
new Thread(t,"b").start();
}
}
class test implements Runnable{
public void run()
{
System.out.println(Thread.currentThread().getName()+"-->start");
Thread.yield();//礼让
System.out.println(Thread.currentThread().getName()+"-->end");
}
}
例2:
public class n {
public static void main(String[]args)
{
new Thread(()->
{
for(int i=0;i<5;i++)
{
System.out.println("a"+i);
}
}).start();
for(int i=0;i<5;i++)
{
if(i%2==0)
{
Thread.yield();
}
System.out.println("b"+i);
}
}
}