Java 创建线程池 批量执行任务

ThreadPoolExecutor threadPoolExecutor =
                new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors() * 2,
                        (int) (Runtime.getRuntime().availableProcessors() / (1 - 0.9)), 200, TimeUnit.MILLISECONDS,
                        new LinkedBlockingQueue<Runnable>(20), Executors.defaultThreadFactory(),
                        new ThreadPoolExecutor.CallerRunsPolicy());
        //线程释放
        threadPoolExecutor.setKeepAliveTime(200, TimeUnit.MILLISECONDS);
        threadPoolExecutor.allowCoreThreadTimeOut(true);
        ExecutorService executor = threadPoolExecutor;

        CompletionService<Object> completionService =
                new ExecutorCompletionService<>(
                        executor);


        try {

            final List<Future<Object>> futures = new ArrayList<>();
            int i = 0;
            // 多线程启动解析服务
            for (AutomateVO automateVO : automateVOList) {
                i++;
                Future<Object> future = completionService
                        .submit(new Callable<Object>() {
                            @Override
                            public Object call() {
                                return dosomething...;
                            }
                        });
                if (future != null) {
                    futures.add(future);
                }
            }
            int nums = 0;
            // 判断执行结果
            for (int j = 0; j < futures.size(); j++) {
                nums = j;
                Object paramE = null;
                try {
                    Future future = completionService.poll();
                    if (future != null) {
                        paramE = future.get();
                    }
                } catch (InterruptedException e) {
                    ExceptionUtils.wrapBusinessException(e.getMessage());
                } catch (ExecutionException e) {
                    ExceptionUtils.wrapBusinessException(e.getMessage());
                }
                if (paramE != null) {
                    rstList.add(paramE);
                }
            }
        } finally {
            executor.shutdown();
        }
注意线程池的策略方式,不同的策略方式决定线程如何执行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您好!以下是使用Java线程池实现批量下载文件的示例代码: ```java import java.io.BufferedInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class FileDownloader { private static final int NUM_THREADS = 5; // 线程池中的线程数量 public static void main(String[] args) { List<String> fileUrls = new ArrayList<>(); fileUrls.add("https://example.com/file1.txt"); fileUrls.add("https://example.com/file2.txt"); fileUrls.add("https://example.com/file3.txt"); // 添加更多文件URL到fileUrls列表中 ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS); for (String fileUrl : fileUrls) { executor.execute(() -> { try { downloadFile(fileUrl); } catch (IOException e) { e.printStackTrace(); } }); } executor.shutdown(); } private static void downloadFile(String fileUrl) throws IOException { URL url = new URL(fileUrl); String fileName = getFileNameFromUrl(url); try (BufferedInputStream in = new BufferedInputStream(url.openStream()); FileOutputStream fileOutputStream = new FileOutputStream(fileName)) { byte[] dataBuffer = new byte[1024]; int bytesRead; while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) { fileOutputStream.write(dataBuffer, 0, bytesRead); } } catch (IOException e) { throw e; } System.out.println("Downloaded: " + fileName); } private static String getFileNameFromUrl(URL url) { String[] segments = url.getFile().split("/"); return segments[segments.length - 1]; } } ``` 这段代码创建了一个存储文件URL的列表 `fileUrls`,然后使用线程池 `ExecutorService` 将每个文件的下载任务提交给线程池执行。在 `downloadFile` 方法中,使用输入流从URL中读取文件数据,并使用输出流将数据写入磁盘。每个下载任务都在单独的线程执行。 请注意,此示例仅演示了如何使用线程池实现批量下载文件,并没有处理下载失败、错误处理等其他细节。根据您的实际需求,您可能需要根据情况进行适当的修改和改进。 希望能对您有所帮助!如果您有任何其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值