yield

线程的礼让:

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

程序:

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
原文地址:https://www.cnblogs.com/da-peng/p/10019423.html