Files
HW-08-Basic-Multithreading/src/main/java/Main.java
T
farnam_jhn 5eb6343ba6 Added REPORT.md for the theoretical questions
Finished ProgressMonitor, DownloadWorker and Main classes.
2026-06-02 14:17:00 +03:30

94 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("Chunk with id: " + chunk.getChunkId() + " is assigned to Thread: " + workerThread.getName());
}
// 4. Create and start monitor thread
ProgressMonitor monitor = new ProgressMonitor(config, chunks);
Thread monitorThread = new Thread(monitor, "Progress-Monitor");
// 5. Start worker threads & monitor thread
monitorThread.start();
for (Thread workerThread : workerThreads){
workerThread.start();
}
// 6. Wait for the workers to finish
for (Thread workerThread : workerThreads){
try {
workerThread.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
try {
monitorThread.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
// 7. Print final report
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.");
}
}