public class TestYield {
public static void main(String args[]) {
MyThread3 t1 = new MyThread3("t1");
MyThread3 t2 = new MyThread3("t2");
t1.start();
t2.start();
}
}class MyThread3 extends Thread {
MyThread3(String s) {
super(s);
}
public void run() {
for(int i=0;i<=100;i++) {
System.out.println( getName()+": " + i);
if(i%10==0) {
yield();
}
}
}
}这个程序本来是应该没执行到10的整数就应该让出线程,可运行结果t2这个线程执行到输出10的时候怎么是继续执行输出11啊,其他的都正常
public static void main(String args[]) {
MyThread3 t1 = new MyThread3("t1");
MyThread3 t2 = new MyThread3("t2");
t1.start();
t2.start();
}
}class MyThread3 extends Thread {
MyThread3(String s) {
super(s);
}
public void run() {
for(int i=0;i<=100;i++) {
System.out.println( getName()+": " + i);
if(i%10==0) {
yield();
}
}
}
}这个程序本来是应该没执行到10的整数就应该让出线程,可运行结果t2这个线程执行到输出10的时候怎么是继续执行输出11啊,其他的都正常
public static void yield()
暂停当前正在执行的线程对象,并执行其他线程。 只是执行太快了,所以没感觉而已
t1,t2在i=10时都让出了CPU,此时,因为线程还没结束,系统会继续分配CPU时间给线程,但是分给谁是随机的,这样就有可能又分给了t2