Thread.yield() 礼让方法
假如有A,B两个线程,A线程调用礼让方法,会从cpu调度中出来,这个时候A和B都是就绪状态,有可能下次cpu还是会调度A线程,所以可能会礼让不成功。
public class TestThreadYield implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" start");
Thread.yield();
System.out.println(Thread.currentThread().getName()+" end");
}
public static void main(String[] args) {
TestThreadYield threadYield = new TestThreadYield();
new Thread(threadYield,"A").start();
new Thread(threadYield,"B").start();
}
}
运行结果有可能礼让成功,也可能不成功
A start
B start
B end
A end
A start
B start
A end
B end
网友评论