首页 > 其他 > 详细

yield

时间:2018-11-26 12:52:59      阅读:144      评论:0      收藏:0      [点我收藏+]

线程的礼让:

当轮到一个线程执行任务,但是这个线程处理一个不是很重要的事情的时候,可以让大家来一次抢占的机会

程序:

package concurrent._yield;

public class Demo {
    public static void main(String[] args) {
        ThreadA a = new ThreadA("a");
        ThreadA b = new ThreadA("b");
        a.start();
        b.start();
    }

}

class ThreadA extends Thread{
    public ThreadA(String name){
        super(name);
    }
    @Override
    public void run() {
        String threadName = this.getName();
        for(int i = 0 ;i < 10 ; i ++){
            long now = System.currentTimeMillis();
            while(System.currentTimeMillis() - now <10){

            }
            System.out.println(threadName + "---" + i);
            Thread.yield();
        }
    }
}

结果:

a---0
b---0
b---1
a---1
a---2
b---2
a---3
b---3
a---4
b---4
a---5
b---5
a---6
b---6
a---7
b---7
a---8
b---8
a---9
b---9

 

yield

原文:https://www.cnblogs.com/da-peng/p/10019423.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!