zoukankan      html  css  js  c++  java
  • Thread.yield

    它与sleep()类似,只是不能由用户指定暂停多长时间,并且yield()方法只能让同优先级的线程有执行的机会

    package gov.mof.fasp2.gcfr.adjustoffset.adjust;
    
    public class Main {
        public static void main(String[] args) {
            Runnable r1 = new Processor();
            Thread t1 = new Thread(r1, "t1");
            t1.start();
    
            Thread t2 = new Thread(r1, "t2");
            t2.start();
        }    
    }
    class Processor implements Runnable {
        
        public void run() {
            for (int i=0; i<50; i++) {
                System.out.println(Thread.currentThread().getName() + "," + i);
                if (i % 10 == 0) {
                    System.out.println(Thread.currentThread().getName() +"--------------");
                    //采用yieid可以将CPU的使用权让给同一个优先级的线程
                    Thread.yield();
                }
            }    
        }    
    }

    如果t1线程执行了yield,那么就会暂停,t2开始执行。t2执行yield时会暂停,t1开始又执行。如此交替执行。结果如下:

  • 相关阅读:
    JS高级程序设计 第三章笔记
    JS高级程序设计第二章
    JS高级程序设计 第一章读书笔记
    markdown 尝试
    实验九
    第六章总结
    实验五
    第五章总结
    实验四
    实验三
  • 原文地址:https://www.cnblogs.com/hkdpp/p/10522895.html
Copyright © 2011-2022 走看看