【发布时间】:2012-04-02 02:03:16
【问题描述】:
关于 Thread.yield() 方法的一些问题。我的理解是当我们调用Thread.Yield()时,当前运行的线程会回到可运行状态。所以依赖线程优先级的线程调度器会执行下一个更高优先级的线程。现在我有一个示例程序。请看下文。
package thread;
public class YieldTest implements Runnable {
@Override
public synchronized void run() {
System.out.println(Thread.currentThread().getName()+", executing..");
for(int i = 0 ; i <5;i++){
if(i==2){
Thread.yield();
System.out.println(Thread.currentThread().getName()+": "+i+" yielded()");
/*try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+": "+i+" yielded()");
} catch (InterruptedException e) {
e.printStackTrace();
}*/
}else{
System.out.println(Thread.currentThread().getName()+": "+i);
}
}
}
public static void main(String[] args) {
YieldTest test = new YieldTest();
Thread t1 = new Thread(test);
t1.setName("A");
t1.setPriority(9);
Thread t2 = new Thread(test);
t2.setName("B");
Thread t3 = new Thread(test);
t3.setName("C");
t2.setPriority(6);
t2.setPriority(4);
t1.start();
t2.start();
t3.start();
}
}
在这里,我总是通过以下方式获取输出,
A, executing..
A: 0
A: 1
A: 2 yielded()
A: 3
A: 4
C, executing..
C: 0
C: 1
C: 2 yielded()
C: 3
C: 4
B, executing..
B: 0
B: 1
B: 2 yielded()
B: 3
B: 4
现在的问题是 yield() 方法应该回到可运行状态,其他线程应该执行。所以输出应该类似于以下方式
A,正在执行.. 答:0 答:1 A: 2 产生()
C,正在执行.. C: 0 C: 1 C: 2 产生()
A: 3
A: 4
B,执行.. 乙:0 乙:1 B: 2 产生()
C: 3
C: 4
B: 3
B: 4
另外,线程优先级如何。不保证为什么我们需要线程优先级?如果我错了请纠正我。
【问题讨论】:
-
您真正想解决什么问题?调用
yield()可能不是最好的解决方案。 -
有关
yield()的更多信息,请参阅this question。 -
在这种特殊情况下,如果线程 A 在 B 有时间启动之前完成,我不会感到惊讶。
标签: java