yield方法是 Thread类的方法
/**
* Causes the currently executing thread object to temporarily pause
* and allow other threads to execute.
*/
public static native void yield();
从注释上来看
*使当前正在执行的线程对象暂时暂停
*并允许其他线程执行。
写个demo测试一下
public class TestYield {
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable(){
public void run(){
System.out.println("开始抢占线程1:"+Thread.currentThread().getName());
Thread.yield();
System.out.println("线程运行结束1:"+Thread.currentThread().getName());
}
});
Thread t2 = new Thread(new Runnable(){
public void run(){
System.out.println("开始抢占线程2:"+Thread.currentThread().getName());
System.out.println("线程运行结束2:"+Thread.currentThread().getName());
}
});
t1.start();
t2.start();
}
}
运行结果:
开始抢占线程1:Thread-0
开始抢占线程2:Thread-1
线程运行结束2:Thread-1
线程运行结束1:Thread-0
如果注释掉 Thread.yield();
开始抢占线程2:Thread-1
线程运行结束2:Thread-1
开始抢占线程1:Thread-0
线程运行结束1:Thread-0