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;
}
}