美文网首页
线程的礼让_Thread.yield()方法

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

作者: 暖熊熊 | 来源:发表于2017-06-08 13:46 被阅读0次

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

执行结果

可以看到有的礼让,有的没有礼让,这是为什么,我们来看一下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}   

相关文章

  • 线程礼让

    Thread.yield() 礼让方法 假如有A,B两个线程,A线程调用礼让方法,会从cpu调度中出来,这个时候A...

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

    在多线程里面有各种各样的方法,其中有一个礼让的方法很有意思,现实生活中所谓的礼让,就是“委屈自己方便他人”!比如过...

  • Java基础-线程-yeild

    Java线程中的Thread.yield( )方法,译为线程让步。顾名思义,就是说当一个线程使用了这个方法之后,它...

  • java 并发 yield()方法-线程让步

    线程让步。Thread.yield()方法作用是:暂停当前正在执行的线程对象,并执行其他线程。但是,实际中无法保证...

  • 浅谈Thread.yield()方法

    概念 当调用Thread.yield()方法时,会给线程调度器一个当前线程愿意让出CPU使用的暗示,但是线程调度器...

  • Java——yield()作用

    Thread.yield()方法作用是:暂停当前正在执行的线程对象,并执行其他线程。 yield()应该做的是让当...

  • 线程

    join方法加入线程方法 interrupt终止线程 yield礼让方法 暂不介绍啦,因为具体要看CPU 线程设置...

  • Thread.yield() 方法的作用

    Thread.yield() 方法,使当前线程由执行状态,变成为就绪状态,让出cpu时间,在下一个线程执行时候,此...

  • 线程的五种状态

    yield:线程礼让,线程回到就绪态sleep:让线程进入休眠状态wait:等待,是object类的方法,当前线程...

  • 多线程-H2O 生成的3种写法

    写法1:使用volatile修饰变量控制, Thread.yield()使线程让出当前时间片给其他线程执行。 ...

网友评论

      本文标题:线程的礼让_Thread.yield()方法

      本文链接:https://www.haomeiwen.com/subject/hrzzfxtx.html