其他分享
首页 > 其他分享> > 线程礼让

线程礼让

作者:互联网

/**
 * @Author:gaoyuan
 * @Description:线程礼让 yield
 * @DateTime:2021/1/21 21:40
 **/
public class Comity {
    public static void main(String[] args) {
        //创建对象
        ThreadYield threadYield = new ThreadYield();
        ThreadYield threadYield2 = new ThreadYield();
        threadYield.setName("55开");
        threadYield2.setName("zzzz");

        threadYield.start();
        threadYield2.start();

    }
}

class ThreadYield extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(getName() + "------" + i);
            yield();
            //暂停当前正在执行的线程对象
            //并执行其他线程
            //虽然放弃了CPU的执行权,但是我们java当中采用的是抢占式的调度方式
            //所以下一次不一定是谁抢到
        }

    }
}
55开------0
zzzz------0
55开------1
55开------2
zzzz------1
55开------3
55开------4
zzzz------2
zzzz------3
zzzz------4
55开------5
zzzz------5
zzzz------6
55开------6
zzzz------7
55开------7
zzzz------8
55开------8
55开------9
zzzz------9

标签:ThreadYield,55,zzzz,线程,------,public,礼让
来源: https://blog.csdn.net/gy99csdn/article/details/112973250