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

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

  1. public class yeld {  
  2.   
  3.     public static void main(String[] args) {  
  4.         ThreadDemo demo = new ThreadDemo();  
  5.         Thread thread = new Thread(demo, "花花");  
  6.         Thread thread1 = new Thread(demo, "草草");  
  7.         thread.start();  
  8.         thread1.start();  
  9.     }  
  10. }  
  11.   
  12. class ThreadDemo implements Runnable {  
  13.   
  14.     @Override  
  15.     public void run() {  
  16.         for (int i = 0; i < 5; i++) {  
  17.             if (i == 3) {  
  18.                 System.out.println("当前的线程是     " + Thread.currentThread().getName());  
  19.                 Thread.currentThread().yield();  
  20.             }  
  21.             System.out.println("执行的是    " + Thread.currentThread().getName());  
  22.         }  
  23.   
  24.     }  
  25.   
  26. }  
运行的结果看一下
  1. 执行的是    草草  
  2. 执行的是    草草  
  3. 执行的是    草草  
  4. 当前的线程是     草草//并没有礼让  
  5. 执行的是    草草  
  6. 执行的是    草草  
  7. 执行的是    花花  
  8. 执行的是    花花  
  9. 执行的是    花花  
  10. 当前的线程是     草草//礼让啦  
  11. 执行的是    花花  
  12. 执行的是    花花  

可以看到有的让了,有的没有让,这是为什么嘞,我们来看一下yield()方法的源码注释,第一行就给了答案:  

         A hint to the scheduler that the current thread is willing to yield  

  1. its current use of a processor. The scheduler is free to ignore this  
  2. hint.  
  3.     //暗示调度器让当前线程出让正在使用的处理器。调度器可自由地忽略这种暗示。也就是说让或者不让是看心情哒    
  4. <p> Yield is a heuristic attempt to improve relative progression  
  5. between threads that would otherwise over-utilise a CPU. Its use  
  6. should be combined with detailed profiling and benchmarking to  
  7. ensure that it actually has the desired effect.  
  8.   
  9. <p> It is rarely appropriate to use this method. It may be useful  
  10. for debugging or testing purposes, where it may help to reproduce  
  11. bugs due to race conditions. It may also be useful when designing  
  12. concurrency control constructs such as the ones in the  
  13. {@link java.util.concurrent.locks}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值