Java中批量執行的方法有以下幾種:
List<String> list = Arrays.asList("a", "b", "c");
for (String str : list) {
// 執行相同的操作
}
List<String> list = Arrays.asList("a", "b", "c");
List<Thread> threads = new ArrayList<>();
for (String str : list) {
Thread thread = new Thread(() -> {
// 執行相同的操作
});
threads.add(thread);
thread.start();
}
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
ExecutorService executor = Executors.newFixedThreadPool(10);
List<String> list = Arrays.asList("a", "b", "c");
List<Future<?>> futures = new ArrayList<>();
for (String str : list) {
Future<?> future = executor.submit(() -> {
// 執行相同的操作
});
futures.add(future);
}
for (Future<?> future : futures) {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
executor.shutdown();