java Thread yield()方法的理解

先看一下源碼 yield()是一個native方法也就是說是C或者C++實現的java

/**
     * 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();

概念: 當調用Thread.yield()的時候,會給線程調度器一個當前線程願意出讓CPU的使用的暗示,可是線程調度器可能會忽略這個暗示。app

代碼ide

public class Demo3 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    System.out.println("當前線程爲: "+ Thread.currentThread().getName()+ i);
                    if (i == 5){
                        Thread.yield();
                    }
                }
            }
        };

        Thread thread = new Thread(runnable,"A");
        Thread thread1 = new Thread(runnable,"B");
        thread.start();
        thread1.start();
    }
}

第一次執行結果this

當前線程爲: A0
當前線程爲: B0
當前線程爲: A1
當前線程爲: B1
當前線程爲: A2
當前線程爲: B2
當前線程爲: A3
當前線程爲: B3
當前線程爲: A4
當前線程爲: B4
當前線程爲: A5
當前線程爲: B5
當前線程爲: A6
當前線程爲: B6
當前線程爲: A7
當前線程爲: B7
當前線程爲: B8
當前線程爲: A8
當前線程爲: A9
當前線程爲: B9
第二次執行結果線程

當前線程爲: B0
當前線程爲: B1
當前線程爲: B2
當前線程爲: B3
當前線程爲: B4
當前線程爲: B5
當前線程爲: B6
當前線程爲: B7
當前線程爲: B8
當前線程爲: B9
當前線程爲: A0
當前線程爲: A1
當前線程爲: A2
當前線程爲: A3
當前線程爲: A4
當前線程爲: A5
當前線程爲: A6
當前線程爲: A7
當前線程爲: A8
當前線程爲: A9
第三次執行結果debug

當前線程爲: A0
當前線程爲: A1
當前線程爲: A2
當前線程爲: A3
當前線程爲: A4
當前線程爲: A5
當前線程爲: A6
當前線程爲: A7
當前線程爲: A8
當前線程爲: A9
當前線程爲: B0
當前線程爲: B1
當前線程爲: B2
當前線程爲: B3
當前線程爲: B4
當前線程爲: B5
當前線程爲: B6
當前線程爲: B7
當前線程爲: B8
當前線程爲: B9
第四次執行結果code

當前線程爲: A0
當前線程爲: A1
當前線程爲: A2
當前線程爲: A3
當前線程爲: A4
當前線程爲: A5
當前線程爲: A6
當前線程爲: A7
當前線程爲: A8
當前線程爲: A9
當前線程爲: B0
當前線程爲: B1
當前線程爲: B2
當前線程爲: B3
當前線程爲: B4
當前線程爲: B5
當前線程爲: B6
當前線程爲: B7
當前線程爲: B8
當前線程爲: B9
第五次執行結果get

當前線程爲: A0
當前線程爲: B0
當前線程爲: A1
當前線程爲: B1
當前線程爲: A2
當前線程爲: B2
當前線程爲: A3
當前線程爲: B3
當前線程爲: A4
當前線程爲: B4
當前線程爲: A5
當前線程爲: B5
當前線程爲: A6
當前線程爲: B6
當前線程爲: A7
當前線程爲: B7
當前線程爲: B8
當前線程爲: A8
當前線程爲: A9
當前線程爲: B9
說明每次執行的可能都不同,可是當執行到i == 5時候當前線程可能繼續執行也可能讓B執行。源碼

相關文章
相關標籤/搜索