【发布时间】:2021-06-09 13:33:02
【问题描述】:
我目前正在学习多线程,但我在理解我的代码中出了什么问题时遇到了一些问题。
我试图通过调用我的函数threadPopulateList() 用随机数据填充两个列表。据我了解,这应该并行启动两个线程,因为我调用了两次该方法。
但是,使用 threadmethod 时,我的执行时间增加了约 50%。
代码:
public class Main {
public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
long start=System.currentTimeMillis();
/**Populate lists after eachother gives --> 4211 ms */
// List<DATA>list1normal = populateNormal(9999999);
// List<DATA>list2normal = populateNormal(9999999);
/**Populate list simoultaniously/parralel --> 6500ms???*/
List<DATA>list1normal = threadPopulateList(9999999);
List<DATA>list2normal = threadPopulateList(9999999);
long stop = System.currentTimeMillis();
long executionTime = stop-start;
System.out.println(executionTime+" ms");
}
/**Method to populate list*/
static List<DATA> populateNormal(int amount){
List<DATA>data = new ArrayList<>();
Random rn = new Random();
for (int i = 0; i < amount; i++) {
data.add(new DATA(rn.nextInt(1000),rn.nextInt(1000), rn.nextInt(1000)));
}
return data;
}
/**Method to start a thread for each call so list will populate simoultiously*/
static List<DATA> threadPopulateList(int amount) throws InterruptedException, ExecutionException {
ExecutorService executor = Executors.newFixedThreadPool(2);
List<DATA> data = new ArrayList<>();
Random rn = new Random();
Callable<List<DATA>> callable = () -> {
for (int i = 0; i < amount; i++) {
data.add(new DATA(rn.nextInt(1000), rn.nextInt(1000), rn.nextInt(1000)));
}
return data;
};
Future<List<DATA>> result = executor.submit(callable);
executor.shutdown();
return result.get();
}
}
【问题讨论】:
-
您正在创建 两个 列表,两个列表都由 单个 线程填充。您可能想要创建一个由 两个 线程填充的 单个 列表?
-
无关:遵循 java 命名约定。类名采用大写字母,而不是 SOLIDUPPERCASE。您在那里所做的事情极具误导性,因为人们很容易假设 DATA 不是类名而是泛型类型参数。
-
@Lino 我的意图是同时填写 2 个单独的列表,所以在并行中。然后看看它有多快。 2 个任务 2 个线程
标签: java multithreading concurrency multitasking