gpt4 book ai didi

java - Java 程序的输出

转载 作者:行者123 更新时间:2023-12-02 06:13:52 25 4
gpt4 key购买 nike

我正在尝试运行已创建 3 个线程的程序。

1) 苹果.Java

package Test;
import java.util.Random;

public class Apple implements Runnable{

String name;
int time;
Random r = new Random();

public Apple(String s){

name = s;
time = r.nextInt(999);
}

public void run(){

try{
System.out.printf("%s is sleeping for %d\n", name, time);
//because we want each thread to sleep for random time.
Thread.sleep(time);
System.out.printf("%s is done\n" + name);

}catch(Exception e){}
}
}

2) 线程测试.java

package Test;

public class Anand {

public static void main(String[] args){

Thread t1 = new Thread(new Apple("one"));
Thread t2 = new Thread(new Apple("two"));
Thread t3 = new Thread(new Apple("three"));
t1.start();
t2.start();
t3.start();
}
}

预期输出是

one is sleeping for 934
three is sleeping for 383
two is sleeping for 228
two is done.
three is done.
one is done.

实际输出是:

当我将“ABC.java”作为 Java 应用程序运行时,我得到以下输出:

one is sleeping for 934
three is sleeping for 383
two is sleeping for 228

这里我无法理解为什么下面的语句没有被执行?或者为什么我没有在控制台上得到以下语句的输出?

 System.out.printf("%s is done\n" + name);

最佳答案

此代码中的实际错误是:

java.util.MissingFormatArgumentException: Format specifier '%s'

ideone demo

因为这个:

System.out.printf("%s is done\n" + name);

应该是:

System.out.printf("%s is done\n", name);

请考虑这是一个说明性示例,说明为什么应该很少(如果有的话)使用空 catch block 。

}catch(Exception e){}  // Aaaargh! Nope nope nope.

至少,打印堆栈跟踪:

}catch(Exception e){
e.printStackTrace();
}

而且,请确保您等待线程完成:

t1.join();
t2.join();
t3.join();

这更像是一个好习惯(类似于关闭流),而不是这个特定示例所必需的东西。

From the Javadoc of Thread :

The Java Virtual Machine continues to execute threads until either of the following occurs:

  • The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
  • All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.

OP 的代码不调用exit,所以这里不相关。所有线程都是非守护线程,因此执行将继续,直到它们全部完成(以某种方式)。换句话说,JVM 会隐式插入一个join() 来等待所有线程完成。因此,正如其他答案中所建议的那样,插入一个join,实际上并没有做任何改变代码行为的事情。

关于java - Java 程序的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47749445/

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