Linux 拨号vps windows公众号手机端

Java批量执行的方法有哪些

lewis 7年前 (2019-01-11) 阅读数 8 #程序编程
文章标签 Java

Java中批量执行的方法有以下几种:

  1. 使用for循环进行批量执行:通过for循环遍历一个集合或数组,然后依次执行相同的操作。
List<String> list = Arrays.asList("a", "b", "c");
for (String str : list) {
// 执行相同的操作
}
  1. 使用多线程进行批量执行:通过创建多个线程,每个线程执行相同的操作,从而实现批量执行。
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();
}
}
  1. 使用线程池进行批量执行:通过创建一个线程池,将任务提交到线程池中执行,可以控制并发线程数量,提高执行效率。
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();
版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门