线程中yield的用法

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

 

posted @ 2018-07-27 09:40  奋斗的渣渣  阅读(513)  评论(0编辑  收藏  举报