Javaマルチスレッドの使用を記録する
1734 ワード
public List listThreads(List list, final int nThreads ) {
final List fileList = new ArrayList<>();
if (list == null || list.isEmpty()) {
return null;
}
// long start = System.currentTimeMillis();
int size = list.size();
ExecutorService executorService = Executors.newFixedThreadPool(nThreads); //
List> futures = new ArrayList>(nThreads);
for (int i = 0; i < nThreads; i++) {
// ,
final List subList;
if (i == (nThreads - 1)) {
subList = list.subList(size / nThreads * i, size);
} else {
subList = list.subList(size / nThreads * i, size / nThreads * (i + 1));
}
Callable task = new Callable() {
public String call() throws Exception {
int size = 0;
for (String str : subList) {
size++;
//
Thread.sleep(200);
// System.out.println(size*nThreads+"/");
}
return String.valueOf(size);
}
};
futures.add(executorService.submit(task));
}
// for (Future future : futures) {
// ret.append(future.get());
// ret.length(future.get());
// }
executorService.shutdown();
while (true) {
if (executorService.isTerminated()) {
// System.out.println(" , " + String.valueOf((System.currentTimeMillis() - start) / 1000) + " !");
// FileNamesAndNumber.getFileNamesAndNumber(ApiTestManagerForThread.pathname);
break;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(" ");
return fileList;
}