java+yield原理_Java Thread.yield详解

这是Java中的一种线程让步方法,让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.

*

*

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.

*

*

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

看《Java并发编程艺术》这本书,里面有用到Thread.yield方法,来测试Java线程优先级,代码如下:

import java.util.ArrayList;

import java.util.List;

import java.util.concurrent.TimeUnit;

public class Priority {

private static volatile boolean notStart=true;

private static volatile boolean notEnd=true;

public static void main(String[] argvs) throws Exception{

List jobs=new ArrayList();

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

int priority=i<5?Thread.MIN_PRIORITY:Thread.MAX_PRIORITY;

Job job=new Job(priority);

jobs.add(job);

Thread thread=new Thread(job,"Thread:"+i);

thread.setPriority(priority);

thread.start();

}

notStart=false;

TimeUnit.SECONDS.sleep(10);

notEnd=false;

for(Job job:jobs){

System.out.println("Job Priority:"+job.priority+", Count: "+job.jobCount);

}

}

static class Job implements Runnable{

private int priority;

private long jobCount;

public Job(int priority){

this.priority=priority;

}

@Override

public void run() {

while(notStart){

Thread.yield();

}

while(notEnd){

Thread.yield();

jobCount++;

}

}

}

}

跑出结果如下:

Job Priority:1, Count: 6087836

Job Priority:1, Count: 6573345

Job Priority:1, Count: 6024024

Job Priority:1, Count: 6606573

Job Priority:1, Count: 6901572

Job Priority:10, Count: 6118724

Job Priority:10, Count: 5968747

Job Priority:10, Count: 5939391

Job Priority:10, Count: 6206129

Job Priority:10, Count: 6187854

发现即使线程优先级为1和为10的线程,最后获取CPU的次数是差不多的,没有明显差距,线程优先级没有生效。程序的正确性不能依赖于线程的优先级。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值