java - 完整执行时间多线程java
问题描述
我想测量完整的执行时间(当所有线程都完成时)。但是我的代码在这里不起作用,因为当主方法结束而其他线程仍将运行时,因为它们比主方法需要更长的时间来处理。
class Hello extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Hello");
try {
Thread.sleep(500);
} catch (final Exception e) {
}
}
}
}
class Hi extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Hi");
try {
Thread.sleep(500);
} catch (final Exception e) {
}
}
}
}
public class MultiThread {
public static void main(String[] args) {
final long startTime = System.nanoTime();
final Hello hello = new Hello();
final Hi hi = new Hi();
hello.start();
hi.start();
final long time = System.nanoTime() - startTime;
System.out.println("time to execute whole code: " + time);
}
}
我试图找到当程序在单线程v/s多线程上运行时获取执行时间System.nanoTime()
来测量时间。
解决方案
只需添加hello.join()
和hi.join()
之后hi.start()
你最好使用一个ExecutorService
:
public static void main(String[] args) {
final long startTime = System.nanoTime();
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(new Hello());
executor.execute(new Hi());
// finish all existing threads in the queue
executor.shutdown();
// Wait until all threads are finish
executor.awaitTermination();
final long time = System.nanoTime() - startTime;
System.out.println("time to execute whole code: " + time);
}
AnExecutorService
通常正在执行Runnable
or Callable
,但由于Thread
正在扩展Runnable
它们也被执行。
推荐阅读
- php - 将存储在 cookie 中的加密 user_id 与存储在数据库中的 user_id 进行比较
- javascript - 使“继续”按钮在选中项目时出现,在未选中项目时消失
- javascript - jQuery动画从左到右有间隙
- git - Heroku 关于“不要忘记为应用程序的所有其他本地结帐更新 git 遥控器”是什么意思?
- tensorflow - Tensorflow,电影评论预测
- java - 我可以使用类中的 public void 在 ArrayList 中使用它来添加年龄和名称吗?
- android - (没有这样的文件或目录)在 Android 上将 SQLite DB 从外部存储导入到内部存储时出错
- javascript - 使用backboneJS并加载两个不同的jquery版本,但不是一个或另一个
- python - Django Rest Framework POST 失败:“cat_id”列中的空值违反非空约束
- python - Swift + Python:没有名为 librosa 或 pyaudio 的模块