Java 多线程 yield方法

yield()方法

理论上,yield意味着放手,放弃,投降。一个调用yield()方法的线程告诉虚拟机它乐意让其他线程占用自己的位置。这表明该线程没有在做一些紧急的事情。注意,这仅是一个暗示,并不能保证不会产生任何影响。

在Thread.java中yield()定义如下:

1
2
3
4
5
6
7
/**
   * 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-utilize a CPU.
   * Its use should be combined with detailed profiling and benchmarking to ensure that it actually has the desired effect.
   */
 
public static native void yield();

让我们列举一下关于以上定义重要的几点:

  • Yield是一个静态的原生(native)方法
  • Yield告诉当前正在执行的线程把运行机会交给线程池中拥有相同优先级的线程。
  • Yield不能保证使得当前正在运行的线程迅速转换到可运行的状态
  • 它仅能使一个线程从运行状态转到可运行状态,而不是等待或阻塞状态

package java_thread.learn01.c002;

public class yieldTest extends Thread{
    @Override
    public void run(){
        long btime = System.currentTimeMillis();
        int count = 0;
        for(int i = 0;i<50000000;i++){
            Thread.yield();
            count = count + (i + 1);
        }
        long etime = System.currentTimeMillis();
        System.out.println("用时:" +(etime -btime) + "毫秒");    

    }

}


package java_thread.learn01.c002;

public class yieldRun {

    public static void main(String[] args) {
        yieldTest yt = new yieldTest();
        yt.start();

    }

}

上面代码,如果注释Thread.yield();,则时间20毫秒左右,如果不注释,则5030毫秒左右,自己测试看看。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Soyoger

听说打赏的都进了福布斯排行榜。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值