run()
调用(它只是一个普通的方法调用),并使用start()
调用创建了一个重复的线程,该调用生成另一个线程进行处理。然而,start()
调用所需的时间比run()
调用所需的时间更长,后者不是线程调用,为什么会这样呢?
< p>启动调用所需时间:00:00:08:300< /p>
long time = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
Thread thread = new Thread(new Car());
thread.setName(Integer.toString(i));
thread.start();
}
long completedIn = System.currentTimeMillis() - time;
System.out.println(DurationFormatUtils.formatDuration(completedIn,
"HH:mm:ss:SS"));
运行调用所需时间:00:00:01:366
long time = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
Thread thread = new Thread(new Car());
thread.setName(Integer.toString(i));
thread.run();
}
long completedIn = System.currentTimeMillis() - time;
System.out.println(DurationFormatUtils.formatDuration(completedIn,
"HH:mm:ss:SS"));
Runtime.getRuntime().availableProcessors()
来查找可用的核心数,并为每个核心启动一个线程,运行一个紧密循环,反复调用该方法。 - T.J. Crowder