线程池异步下载(模拟1)

import java.util.concurrent.*;
import java.util.stream.Stream;

public class FileDownloader {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        String[] remoteFiles = {"file1.txt", "file2.txt", "file3.txt"};
        String[] localFiles = {"local1.txt", "local2.txt", "local3.txt"};

        String host = "your_host";
        int port = 22;
        String user = "your_user";
        String password = "your_password";

        // 创建一个固定数量的线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(2);  // 限制同时运行的线程数量为2

        // 创建 CompletableFuture 数组来追踪下载任务,返回Boolean表示是否下载成功
        CompletableFuture<Boolean>[] downloadFutures = new CompletableFuture[remoteFiles.length];

        for (int i = 0; i < remoteFiles.length; i++) {
            String remoteFile = remoteFiles[i];
            String localFile = localFiles[i];

            // 使用 supplyAsync 来返回下载的成功与否
            downloadFutures[i] = CompletableFuture.supplyAsync(() -> {
                try {
                    // 下载文件,并返回是否成功
                    boolean success = downloadFile(host, port, user, password, remoteFile, localFile);
                    System.out.println("文件下载成功: " + remoteFile);
                    return success;  // 返回 true 表示下载成功
                } catch (Exception e) {
                    System.out.println("文件下载失败: " + remoteFile);
                    e.printStackTrace();
                    return false;  // 返回 false 表示下载失败
                }
            }, threadPool);
        }

        // 等待所有任务完成
        CompletableFuture<Void> allDownloads = CompletableFuture.allOf(downloadFutures);
        allDownloads.join();  // 阻塞主线程,直到所有任务完成

        // 检查所有任务是否成功
        boolean allSuccessful = Stream.of(downloadFutures)
                .map(CompletableFuture::join)  // 获取每个任务的结果
                .allMatch(result -> result);   // 判断所有结果是否都为 true

        if (allSuccessful) {
            System.out.println("所有文件下载成功!");
        } else {
            System.out.println("某些文件下载失败!");
        }

        // 关闭线程池
        threadPool.shutdown();
    }

    // 模拟的下载方法,返回下载是否成功
    public static boolean downloadFile(String host, int port, String user, String password, String remoteFile, String localFile) throws Exception {
        // 这里实现文件下载的逻辑
        System.out.println("正在下载文件: " + remoteFile);
        // 模拟文件下载时间
        Thread.sleep(1000);

        // 模拟下载成功的结果,返回 true 表示下载成功
        return true;
    }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值