【发布时间】:2021-11-20 18:52:03
【问题描述】:
我有一个执行方法,它一个一个地运行多个测试用例,测试用例在一个字符串数组列表中传递。
我正在尝试以多线程方式运行此测试用例,同时将数据并行写入 CSV 文件。
这是我所做的,但似乎代码没有以多线程方式工作。我在newFixedThreadPool() 中传递了nThread 2,5,7,但执行代码需要相同的时间。
private void executeTest(List<String[]> inputArray) throws ExecutionException, InterruptedException {
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(nThreads);//2, 5, 7
long start = System.currentTimeMillis();
for (String[] listOfArray : inputArray) {
Callable c2 = new Callable() {
public ApiResponse call() {
response = runTestCase(listOfArray);
try {
csvWriter.writeCsv(listOfArray[0], response);
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
};
System.out.println("nThread :"+nThreads);
Future<ApiResponse> result = executor.submit(c2);
result.get();
}
long stop = System.currentTimeMillis();
long timeTaken = stop - start;
System.out.println("Total time taken :"+timeTaken+"No of Theads :"+nThreads);
}
【问题讨论】:
-
将数组列表称为“inputArray”,而将数组本身称为“listOfArray”,这是一种误导。
-
请注意,为 IO 添加更多线程可能不会减少花费的时间,如果您按照我的回答进行调整,csvWriter 需要是线程安全的。
-
是的,csvWriter 是线程安全的。
标签: java multithreading csv callable