gpt4 book ai didi

java - yield 在这里如何运作?

转载 作者:行者123 更新时间:2023-11-29 07:13:39 25 4
gpt4 key购买 nike

方法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");
}

}

我希望我应该看到:

  1. 在 main 然后
  2. 在测试线程中

其余的将是未定义的。但我不明白为什么有时我只看到:In mainBack 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com