A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

public class myThread implements Runnable {
    public void run() {
        int i = 100;
        while(true){
            System.out.println(Thread.currentThread().getName() + ":" + i);
            i--;
            Thread.yield();
            if (i<0) {
                break;
            }
        }
    }
}

public class test {

    public static void main(String[] args) {
        myThread mt = new myThread();
        Thread t1 = new Thread(mt);
        Thread t2 = new Thread(mt);
        t1.setName("线程1");
        t2.setName("线程2");
         
        t1.start();
        t2.start();
    }
}
代码示例如上,我理想的运行结果应该是t1 t2交替运行
比如,
线程1:100
线程1:99
线程1:98
线程2:97
线程2:96
线程1:95


但是在eclipse中却是
线程1:100
线程2:100
线程2:99
线程2:98
线程1:99
线程2:97
线程2:96
线程1:98
线程2:95
线程2:94
线程1:97
线程1:96
线程2:93
线程1:95
线程2:92
线程1:94
线程2:91
线程1:93
线程2:90
。。。。。


这是什么原因呢?
线程释放CPU再重新竞争也应该是运行到thread.yield()才会发生吧?

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马