在多线程里面有各种各样的方法,其中有一个礼让的方法很有意思,现实生活中所谓的礼让,就是“委屈自己方便他人”!比如过马路,汽车礼让行人,当然这是在国外,国内过个斑马线是要看司机的性格的!那么在线程中是个什么情况呢,下面看一下demo
- public class yeld {
- public static void main(String[] args) {
- ThreadDemo demo = new ThreadDemo();
- Thread thread = new Thread(demo, "花花");
- Thread thread1 = new Thread(demo, "草草");
- thread.start();
- thread1.start();
- }
- }
- class ThreadDemo implements Runnable {
- @Override
- public void run() {
- for (int i = 0; i < 5; i++) {
- if (i == 3) {
- System.out.println("当前的线程是 " + Thread.currentThread().getName());
- Thread.currentThread().yield();
- }
- System.out.println("执行的是 " + Thread.currentThread().getName());
- }
- }
- }
- 执行的是 草草
- 执行的是 草草
- 执行的是 草草
- 当前的线程是 草草//并没有礼让
- 执行的是 草草
- 执行的是 草草
- 执行的是 花花
- 执行的是 花花
- 执行的是 花花
- 当前的线程是 草草//礼让啦
- 执行的是 花花
- 执行的是 花花
可以看到有的让了,有的没有让,这是为什么嘞,我们来看一下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}