十五、线程礼让

  • 礼让线程,让当前正在执行的线程暂停,但不阻塞
  • 将线程从运行状态转为就绪状态
  • 让cpu重新调度,礼让不一定成功!看CPU心情

代码:

public class ThreadYield implements Runnable{

    public static void main(String[] args) {
        ThreadYield threadYield = new ThreadYield();
        new Thread(threadYield,"A").start();
        new Thread(threadYield,"B").start();
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"线程开始");
        Thread.yield();
        System.out.println(Thread.currentThread().getName()+"线程结束");
    }
}

结果:

  礼让成功:

  

  礼让失败:

  

posted @ 2022-05-14 20:53  Epiphany8Z  阅读(16)  评论(0编辑  收藏  举报