线程的礼让_Thread.yield()方法

在多线程里面有各种各样的方法,其中有一个礼让的方法很有意思,现实生活中所谓的礼让,就是“委屈自己方便他人”!比如过马路,汽车礼让行人,当然这是在国外!,国内过个斑马线是要看司机的性格的!那么在线程中是个什么情况呢,下面看一下demo

package com.ghw.thread;

class RunnableDemo implements Runnable {
    private String name;

    public RunnableDemo(String name) {
        this.name = name;
    }

    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(name + ":" + i);
            if (i == 5) {
                System.out.println("礼让");
                Thread.yield();
            }
        }
    }
}

public class ThreadDemo03 {

    public static void main(String[] args) {
        RunnableDemo r1 = new RunnableDemo("A");
        RunnableDemo r2 = new RunnableDemo("B");
        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r2);
        t1.start();
        t2.start();
    }
}

线程的礼让_Thread.yield()方法_第1张图片
执行结果

可以看到有的礼让,有的没有礼让,这是为什么,我们来看一下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.  
    //暗示调度器让当前线程出让正在使用的处理器。调度器可自由地忽略这种暗示。也就是说让或者不让是看心情哒    

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.

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}

你可能感兴趣的:(线程的礼让_Thread.yield()方法)