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()才会发生吧? |
|