Java线程中yield()使用方法简介说明

戚薇 Java教程 发布时间:2022-07-15 10:13:46 阅读数:4263 1
下文笔者讲述java线程中yield方法的功能简介说明,如下所示

yield方法的功能

 暂停当前正在执行的线程对象 
 并执行其他线程

注意事项
   其他也包含当前线程
例:
1.首先继承Thread实现一个子类YieldJava265Test,在它的run方法中执行yield()方法。
class YieldJava265Test extends Thread {

  public void run() {
    Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
    System.out.println("YieldJava265Test-run-begin");
    System.out.println("YieldJava265Test-1"); 
    YieldAndSleep.calculate();
    yield();
    System.out.println("YieldJava265Test-2");
    YieldAndSleep.calculate(); 
    System.out.println("YieldJava265Test-run-end");
  }
}
 
2.然后继承Thread实现一个子类SleepJava265Test,在它的run方法中执行sleep方法,用来对比yield方法。
class SleepJava265Test extends Thread {
  
  public void run() {
  Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    System.out.println("SleepJava265Test-run-begin");
    System.out.println("SleepJava265Test-1"); 
    YieldAndSleep.calculate();
    try{  
        sleep(1000);
    } catch (Exception e) {}  
    System.out.println("SleepJava265Test-2"); 
    YieldAndSleep.calculate();  
    System.out.println("SleepJava265Test-run-end");
  }   
}  

 
3.最后分别启动两个YieldJava265Test线程和两个SleepJava265Test线程,观察它们的运行状况
public class YieldAndSleep {

  public static void calculate() {
      for (int i = 0;i<100000000;i++) {
       int j = i*i;
      }
  }
  public static void main(String[] args) {   
    for (int i = 1; i <= 2; i++) { 
      System.out.println("YieldJava265Test().start()-begin");  
      new YieldJava265Test().start(); 
      System.out.println("YieldJava265Test().start()-end");  
    }   
    
    for (int i = 1; i <= 2; i++) { 
      System.out.println("SleepJava265Test().start()-begin");  
      new SleepJava265Test().start(); 
      System.out.println("SleepJava265Test().start()-end");  
    }  
  }  
}
 
4.看一下运行的结果
YieldJava265Test().start()-begin
YieldJava265Test().start()-end
YieldJava265Test().start()-begin
YieldJava265Test-run-begin
YieldJava265Test-1
YieldJava265Test().start()-end
SleepJava265Test().start()-begin
YieldJava265Test-run-begin
YieldJava265Test-1
SleepJava265Test().start()-end
SleepJava265Test().start()-begin
SleepJava265Test().start()-end
SleepJava265Test-run-begin
SleepJava265Test-1 
SleepJava265Test-run-begin
SleepJava265Test-1
YieldJava265Test-2
YieldJava265Test-run-end
YieldJava265Test-2
YieldJava265Test-run-end
SleepJava265Test-2
SleepJava265Test-run-end
SleepJava265Test-2
SleepJava265Test-run-end
 

每次的运行结果可能都不太一样
就拿这次的来分析一下
可以看到第14行输出SleepJava265Test-1
它是在YieldJava265Test-1之后打印出来的
   就是因为在System.out.println("YieldJava265Test-1");
   之后执行了yield();方法
所以从YieldJava265Test线程转换到了SleepJava265Test线程
当然也有可能还是转换到YieldJava265Test自己这个线程。
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaCourse/202207/3978.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者