咱们知道 start() 方法是启动线程,让线程变成就绪状态等待 CPU 调度后执行。java
那 yield() 方法是干什么用的呢?来看下源码。微信
/** * A hint to the scheduler that the current thread is willing to yield * its current use of a processor. The scheduler is free to ignore this * hint. * * <p> Yield is a heuristic attempt to improve relative progression * between threads that would otherwise over-utilise a CPU. Its use * should be combined with detailed profiling and benchmarking to * ensure that it actually has the desired effect. * * <p> It is rarely appropriate to use this method. It may be useful * for debugging or testing purposes, where it may help to reproduce * bugs due to race conditions. It may also be useful when designing * concurrency control constructs such as the ones in the * {@link java.util.concurrent.locks} package. */ public static native void yield();
yield 即 "谦让",也是 Thread 类的方法。它让掉当前线程 CPU 的时间片,使正在运行中的线程从新变成就绪状态,并从新竞争 CPU 的调度权。它可能会获取到,也有可能被其余线程获取到。多线程
下面是一个使用示例。app
/** * 微信公众号:Java技术栈 */ public static void main(String[] args) { Runnable runnable = () -> { for (int i = 0; i <= 100; i++) { System.out.println(Thread.currentThread().getName() + "-----" + i); if (i % 20 == 0) { Thread.yield(); } } }; new Thread(runnable, "栈长").start(); new Thread(runnable, "小蜜").start(); }
这个示例每当执行完 20 个以后就让出 CPU,每次谦让后就会立刻获取到调度权继续执行。this
运行以上程序,能够有如下两种结果。spa
结果1:栈长让出了 CPU 资源,小蜜成功上位。线程
栈长-----29 栈长-----30 小蜜-----26 栈长-----31
结果2:栈长让出了 CPU 资源,栈长继续运行。debug
栈长-----28 栈长-----29 栈长-----30 栈长-----31
而若是咱们把两个线程加上线程优先级,那输出的结果又不同。code
thread1.setPriority(Thread.MIN_PRIORITY); thread2.setPriority(Thread.MAX_PRIORITY);
由于给小蜜加了最高优先权,栈长加了最低优先权,即便栈长先启动,那小蜜仍是有很大的几率比栈长先会输出完的,你们能够试一下。资源
1)yield, sleep 都能暂停当前线程,sleep 能够指定具体休眠的时间,而 yield 则依赖 CPU 的时间片划分。
2)yield, sleep 两个在暂停过程当中,如已经持有锁,则都不会释放锁资源。
3)yield 不能被中断,而 sleep 则能够接受中断。
栈长没用过 yield,感受没什么鸟用。
若是必定要用它的话,一句话解释就是:yield 方法能够很好的控制多线程,如执行某项复杂的任务时,若是担忧占用资源过多,能够在完成某个重要的工做后使用 yield 方法让掉当前 CPU 的调度权,等下次获取到再继续执行,这样不但能完成本身的重要工做,也能给其余线程一些运行的机会,避免一个线程长时间占有 CPU 资源。
动手转发给更多的朋友吧!
更多 Java 多线程技术文章请在Java技术栈微信公众号后台回复关键字:多线程。
本文原创首发于微信公众号:Java技术栈(id:javastack),关注公众号在后台回复 "多线程" 可获取更多,转载请原样保留本信息。