Files
HW-08-Basic-Multithreading/src/main/java/Main.java
T
2026-07-19 06:12:05 +03:30

99 lines
3.0 KiB
Java

import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
System.out.println("=== Simulated Download Manager ===");
// 1. Read config
DownloadConfig config;
try {
config = ConfigReader.readConfig("download_config.txt");
} catch (Exception e) {
System.out.println("Failed to read configuration: " + e.getMessage());
return;
}
System.out.println("File name: " + config.getFileName());
System.out.println("Total size (MB): " + config.getTotalSizeMB());
System.out.println("Chunk count: " + config.getChunkCount());
System.out.println();
// 2. Create chunks
List<ChunkStatus> chunks = ChunkUtils.createChunks(
config.getTotalSizeMB(),
config.getChunkCount()
);
// 3. Create worker threads
List<Thread> workerThreads = new ArrayList<>();
for (ChunkStatus chunk : chunks) {
DownloadWorker worker = new DownloadWorker(chunk, config);
Thread workerThread = new Thread(worker, "Worker-" + chunk.getChunkId());
workerThreads.add(workerThread);
System.out.println("Assigned Chunk #" + chunk.getChunkId()
+ " (" + chunk.getChunkSizeMB() + " MB) to " + workerThread.getName());
}
ProgressMonitor monitor = new ProgressMonitor(config, chunks);
Thread monitorThread = new Thread(monitor, "Progress-Monitor");
monitorThread.start();
for (Thread thread : workerThreads) {
thread.start();
}
for (Thread thread : workerThreads) {
try {
thread.join();
} catch (InterruptedException e) {
System.out.println("Main thread interrupted while waiting for " + thread.getName());
Thread.currentThread().interrupt();
}
}
try {
monitorThread.join();
} catch (InterruptedException e) {
System.out.println("Main thread interrupted while waiting for monitor.");
Thread.currentThread().interrupt();
}
System.out.println();
System.out.println("=== Final Report ===");
int completedChunks = 0;
double downloadedMB = 0.0;
for (ChunkStatus chunk : chunks) {
downloadedMB += chunk.getDownloadedMB();
if (chunk.isCompleted()) {
completedChunks++;
}
System.out.println(
"Chunk " + chunk.getChunkId()
+ ": " + chunk.getDownloadedMB()
+ "/" + chunk.getChunkSizeMB()
+ " MB"
);
}
System.out.println();
System.out.println("Completed chunks: " + completedChunks + "/" + chunks.size());
System.out.println("Downloaded total: " + downloadedMB + "/" + config.getTotalSizeMB() + " MB");
System.out.println("Simulation finished.");
}
}