Thread.yeild方法详解

从原理上讲其实Thread.yeild方法其实只是给线程调度机制一个暗示:我的任务处理的差不多了,可以让给相同优先级的线程CPU资源了;不过确实只是一个暗示,没有任何机制保证它的建议将被采纳;

看一个例子就知道了;

public class LiftOff implements Runnable {

    protected int countDown = 5;

    private static int taskCount = 0;
    private final int id = taskCount++;

    public LiftOff() {

    }

    public LiftOff(int countDown) {
        this.countDown = countDown;
    }

    public String status() {
        // System.out.println(Thread.currentThread().getName());
        return Thread.currentThread().getName() + "#" + id + "(" + (countDown > 0 ? countDown + ")" : "Liftoff!" + ")");
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        /*
         * --countDown:先减去,再赋值
         * countDown--先赋值,再减去
         */
        while (countDown-- > 0) {
            System.out.println(status());
            Thread.yield();// 让步【表示我的任务处理的差不多了,可以让步给其他线程资源了】;CPU资源给其他线程使用;t.join当前线程挂起,直到t线程调用结束后切回
            /*
             * try {
             * TimeUnit.MILLISECONDS.sleep(100);
             * } catch (InterruptedException e) {
             * // TODO Auto-generated catch block
             * // e.printStackTrace();
             * System.err.println("异常终止...");
             * }
             */

        }

    }
View Code
public class ExecuteMethodPool {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();// 无界队列:将为每个任务创建一个线程
        // ExecutorService executorService = Executors.newFixedThreadPool(2);// 有限线程数队列
        // ExecutorService executorService = Executors.newSingleThreadExecutor();// 有限线程数队列

        for (int i = 0; i < 3; i++) {

            executorService.execute(new LiftOff());
        }
        executorService.shutdown();

    }

}

响应结果打印:

pool-1-thread-2#1(4)

pool-1-thread-1#0(4)

pool-1-thread-3#2(4)

pool-1-thread-2#1(3)

pool-1-thread-3#2(3)

pool-1-thread-3#2(2)

pool-1-thread-1#0(3)

pool-1-thread-2#1(2)

pool-1-thread-3#2(1)

pool-1-thread-1#0(2)

pool-1-thread-2#1(1)

pool-1-thread-3#2(Liftoff!)

pool-1-thread-1#0(1)

pool-1-thread-2#1(Liftoff!)

pool-1-thread-1#0(Liftoff!)

 以上标注的两个一样的线程先后执行 并没有遵守yeild给线程调度的建议

原文地址:https://www.cnblogs.com/zhangfengshi/p/9538954.html