作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
方法Thread.yield
:
Causes the currently executing thread object to temporarily pause and allow other threads to execute.
所以在下面的代码中:
public class Test implements Runnable {
private int stopValue;
public Fib(int stopValue){
this.stopValue = stopValue;
}
@Override
public void run() {
System.out.println("In test thread");
for(int i = 0; i < stopValue; i++){
c = i + 1;
}
System.out.println("Result = "+c);
}
public static void main(String[] args){
int defaultStop = 1024;
if(args.length > 0){
defaultStop = Integer.parseInt(args[0]);
}
Thread a = new Thread(new Fib(defaultStop));
System.out.println("In main");
a.setDaemon(true);
a.start();
Thread.yield();
System.out.println("Back in main");
}
}
我希望我应该看到:
在 main
然后 在测试线程中
其余的将是未定义的。但我不明白为什么有时我只看到:In main
和 Back in main
而不是来自 Test
线程的任何打印语句?
最佳答案
yield() 是对操作系统调度的提示,但不提供调度方面的任何保证。它并不总是停顿很长时间。如果您重复调用它,它可能只需要几微秒。
启动线程需要时间,即使您的主线程短暂暂停,它也可能在后台线程启动之前完成。
如您所见,yield() 暂停非常短暂。
long start = System.nanoTime();
long runs = 20000000;
for (int i = 0; i < runs; i++)
Thread.yield();
long time = System.nanoTime() - start;
System.out.printf("Thread.yield() took an average of %,d ns.%n", time / runs);
打印
Thread.yield() took an average of 148 ns.
相比之下,System.nanoTime 在我的机器上花费的时间更长。
long start = System.nanoTime();
long runs = 20000000;
for (int i = 0; i < runs; i++)
System.nanoTime();
long time = System.nanoTime() - start;
System.out.printf("System.nanoTime() took an average of %,d ns.%n", time / runs);
打印
System.nanoTime() took an average of 656 ns.
这两个时间因操作系统和机器而异。
关于java - yield 在这里如何运作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11555334/
我是一名优秀的程序员,十分优秀!