yield示例分析
public class TestYield {
private static final Object lock = new Object();
public static void main(String[] args) {
YieldThread t1 = new YieldThread();
YieldThread t2 = new YieldThread();
t1.start();
t2.start();
/**
* t1得到cpu执行权后,执行run时,获取到lock对象的锁,等到t2执行run时时会被阻塞
* t1执行过程中,每当%4==0时,会进行cpu让步
* 但是由于【yield方法不会释放锁】,所以就算t2得到了cpu执行,但还是会被阻塞
*/
}
static class YieldThread extends Thread{
@Override
public void run() {
synchronized (lock){
for (int i = 0; i < 10; i++) {
System.err.println(this.getName()+"__"+i);
if (i%4==0){
/**
* yield:让步
* 让线程由“运行状态”进入到“就绪状态”
* yield是让出cpu执行时间片,而不释放lock对象的锁
*/
Thread.yield();
}
}
}
}
}
}