java - Java 线程实现
问题描述
下面是我的示例实现代码,其中没有正确线程运行的代码比使用正确线程实现运行的代码花费更少的时间,请告知我犯了什么错误或代码中的问题
@Override
public Integer timeTakenWithoutThreading() {
System.out.println("StartTime" + new Date());
Date startDate = new Date();
int value = 1000000;
int value2 = 2000000;
for (int i = 0; i <= value; i++) {
System.out.println("Value 1" + i);
}
for (int i = 0; i <= value2; i++) {
System.out.println("Value 2" + i);
}
System.out.println("StartTime" + startDate);
System.out.println("endTime" + new Date());
return null;
}
@Override
public String timeTakenWithThreading() {
Date start = new Date();
Date firstThread = new Date();
threadPoolExecutorService.execute(new Runnable() {
final int value = 1000000;
@Override
public void run() {
for (int i = 0; i <= value; i++) {
System.out.println("Thread 1 Value" + i);
}
}
});
threadPoolExecutorService.execute(new Runnable() {
final int value2 = 2000000;
@Override
public void run() {
for (int i = 0; i <= value2; i++) {
System.out.println("Thread 2 Value" + i);
}
System.out.println("Start Date" + start);
System.out.println("End Date" + new Date());
}
});
return "You Will Get Response So Soon But Thread Will Execute At the Background";
}
}```
解决方案
即使没有开始并行执行,您也可以计算开始时间。所以时间测量实际上是错误的。您应该在 Runnable 中初始化开始时间。
例如:
threadPoolExecutorService.execute(new Runnable() {
final int value = 1000000;
@Override
public void run() {
// time started.
Date firstThread = new Date();
System.out.println("First thread started at" + firstThread);
for (int i = 0; i <= value; i++) {
System.out.println("Thread 1 Value" + i);
}
// time ended.
System.out.println("First thread ended at" + new Date());
}
});
也将此应用于第二个线程。您会看到两个线程并行运行。结合起来,它比非线程花费的时间更少。
推荐阅读
- iphone - 如何快速制作带彩光的手电筒(iPhone)?
- c - 从 SIGINT 句柄调用精心设计的函数 - 什么时候可以?
- reactjs - react redux:如果调用了套接字事件,则调用函数
- arrays - 使用 jq 格式化为 CSV JSON 文件
- php - 如何在 wordpress 的不同页面上使用一个模板?
- c# - Aspose 目录不会更新字段 (C#)
- php - “MySQL 服务器已消失”,然后是“得到一个大于 'max_allowed_packet' 字节的数据包”
- hdfs - 更改 avro/hdfs 的文件编码
- laravel - 我希望每封电子邮件对于某个字段的 id 都是唯一的。如何在 laravel 5 中进行验证
- javascript - 如何在 React Native 中找出错误和位置