线程让步—yield()

线程让步Thread.yield():当前线程已经把重要的部分执行完毕,此时可以切换线程。

class MyThread implements Runnable {
    public void run() {
        int i = 0;
        while(i < 6) {
            System.out.println(Thread.currentThread() + " a = " + i);
            i++;
            Thread.yield();
        }
    }
}
public class Demo1 {

    public static void main(String[] args) throws Exception {
        Thread t1 = new Thread(new MyThread(),"t1");
        Thread t2 = new Thread(new MyThread(),"t2");
        t1.start();
        t2.start();
    }

}

输出:

Thread[t1,5,main] a = 0
Thread[t2,5,main] a = 0
Thread[t1,5,main] a = 1
Thread[t2,5,main] a = 1
Thread[t1,5,main] a = 2
Thread[t2,5,main] a = 2
Thread[t2,5,main] a = 3
Thread[t2,5,main] a = 4
Thread[t1,5,main] a = 3
Thread[t1,5,main] a = 4
Thread[t2,5,main] a = 5
Thread[t1,5,main] a = 5

再次强调不可以依赖线程的顺序,线程的调度是非确定的。

posted @ 2020-03-15 22:24  卑微芒果  Views(300)  Comments(0Edit  收藏  举报