diff --git a/README.md b/README.md
index e5cc79c..506c3f4 100644
--- a/README.md
+++ b/README.md
@@ -1,202 +1,53 @@
-# Eighth Assignment: Multithreading Basics
+
-## Table of contents
-- [Introduction](#introduction)
-- [Objectives 🎯](#objectives-)
-- [Theoretical Questions 📝](#theoretical-questions-)
-- [Practical Questions 💻](#practical-questions-)
-- [Evaluation ⚖️](#evaluation-)
-- [Submission ⌛](#submission-)
-- [Additional Resources 📚](#additional-resources-)
+# گزارش پروژه هشتم - برنامهنویسی پیشرفته
-## Important Note:
-This project is configured as a **Maven project**. If you're opening this project in an IDE (like IntelliJ IDEA or VS Code), please ensure you import it as a Maven project so that dependencies and build settings are recognized automatically.
-
-To run the project from the command line, use:
-```bash
-mvn compile
-mvn exec:java -Dexec.mainClass="Main"
-```
-
-## Introduction
-Welcome to your Eighth Advanced Programming (AP) Assignment. This project is divided into two main sections:
-
-1. **Theoretical Questions**: Analyze key multithreading concepts (Start vs Run, Daemon threads, and Lambdas).
-2. **Practical Questions**: Implement a **Simulated Download Manager**. You will use Java Threads to simulate downloading a file in multiple chunks concurrently.
-
-> **⚠️ Note:** This is a **local simulation only**. There is no actual network activity, URL connection, or socket programming involved. The goal is to practice thread management and state observation.
-
-## Objectives 🎯
-
-By completing this assignment, you will:
-- Apply **multithreading** basics using the `Thread` class and `Runnable` interface.
-- Understand how to manage multiple worker threads performing independent tasks.
-- Implement a monitor thread to observe the progress of other threads.
-- Practice using `start()` and `join()` for thread lifecycle management.
-
-## Theoretical Questions 📝
-**Note: Please answer these questions in a Markdown file (Report.md) and place it in the root directory of your fork. Include code or screenshots where you see fit.**
-
-### 1. `start()` vs `run()`
-
-```java
-public class StartVsRun {
- static class MyRunnable implements Runnable {
- public void run() {
- System.out.println("Running in: " + Thread.currentThread().getName());
- }
- }
- public static void main(String[] args) throws InterruptedException {
- Thread t1 = new Thread(new MyRunnable(), "Thread-1");
- System.out.println("Calling run()");
- t1.run();
- Thread.sleep(100);
-
- Thread t2 = new Thread(new MyRunnable(), "Thread-2");
- System.out.println("Calling start()");
- t2.start();
- }
-}
-```
-
-**Questions:**
-
-- What output do you get from the program? Why?
-
-- What’s the difference in behavior between calling `start()` and `run()`?
-
----
-
-### 2. Daemon Threads
-
-```java
-public class DaemonExample {
- static class DaemonRunnable implements Runnable {
- public void run() {
- for(int i = 0; i < 20; i++) {
- System.out.println("Daemon thread running...");
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- //[Handling Exception...]
- }
- }
- }
- }
- public static void main(String[] args) {
- Thread thread = new Thread(new DaemonRunnable());
- thread.setDaemon(true);
- thread.start();
- System.out.println("Main thread ends.");
- }
-}
-```
-
-**Questions:**
-- What output do you get from the program? Why?
-
-- What happens if you remove `thread.setDaemon(true)`?
-
-- What are some real-life use cases of daemon threads?
-
-
----
-
-### 3. A shorter way to create threads
-
-```java
-public class ThreadDemo {
- public static void main(String[] args) {
- Thread thread = new Thread(() -> {
- System.out.println("Thread is running using a ...!");
- });
-
- thread.start();
- }
-}
-```
-
-**Questions:**
-- What output do you get from the program?
-
-- What is the `() -> { ... }` syntax called?
-
-- How is this code different from creating a class that extends `Thread` or implements `Runnable`?
-
-
-## Practical Questions 💻
-
-### Simulated Download Manager
-You are tasked with completing a skeleton project for a download manager. The application reads a configuration file, splits a "file" into several chunks, and assigns each chunk to a dedicated worker thread.
-
-#### 🏗 Project Structure
-- `src/main/resources/download_config.txt`: Contains simulation parameters (file size, chunk count, delays).
-- `DownloadWorker.java`: The logic for simulating a chunk download (needs implementation).
-- `ProgressMonitor.java`: A thread that periodically prints the total progress (needs implementation).
-- `Main.java`: The entry point that initializes chunks, starts threads, and waits for completion.
-- `ChunkStatus.java`: Data class holding the state of individual chunks.
-
-#### 🛠 What You Need to Do
-In the provided source code, look for **`// TODO`** comments. You must:
-
-1. **Implement `DownloadWorker`**:
- - Record start/end times for each chunk.
- - Use a loop to simulate progress based on the random delays and step sizes provided in the config.
- - Update the shared `ChunkStatus` object so the monitor can see progress.
-2. **Implement `ProgressMonitor`**:
- - Periodically calculate the total downloaded megabytes across all chunks.
- - Exit gracefully once all chunks are marked as completed.
-3. **Complete `Main`**:
- - Properly instantiate and `start()` the worker threads and the monitor thread.
- - Use `join()` to ensure the main thread waits for all workers to finish before printing the final report.
-
-#### ⚙️ Configuration
-The simulation behavior is controlled by `src/main/resources/download_config.txt`. You can modify these values to test different scenarios (e.g., more chunks or faster/slower speeds).
+**نام دانشجو:** امیرعلی امیری
+**درس:** برنامهنویسی پیشرفته (AP)
---
-## Bonus Tasks 🌟
-- Download Speed and ETA:
- - Calculate and display the current overall download speed during the simulation.
- - Estimate and show the remaining time (ETA) based on the current progress and speed.
+## بخش اول: مقایسه `start()` و `run()`
-- User Interface (UI):
- - Improve the console output or design a simple UI that presents download progress in a cleaner and more intuitive way.
- - Make the simulation easier to follow by showing chunk activity, total progress, and final results in a user-friendly format.
+### ۱. خروجی برنامه و دلیل آن
+* **خروجی فراخوانی `t1.run()`:** عبارت `Running in: main`
+* **خروجی فراخوانی `t2.start()`:** عبارت `Running in: Thread-2`
-- Real-Time Progress Bar:
- - Implement a real-time progress bar that updates in place instead of printing a new line each time.
- - Show smooth progress growth in the console so the output looks more like a real download manager.
+**دلیل:** هنگام فراخوانی مستقیم متد `t1.run()`، نخ (Thread) جدیدی ساخته نمیشود؛ به همین دلیل کدهای درون این متد مانند یک متد معمولی و به صورت خطبهخط، داخل همان نخ فعلی (یعنی نخ `main`) اجرا میشوند.
+اما با فراخوانی متد `t2.start()`، به ماشین مجازی جاوا (JVM) درخواست داده میشود تا یک نخ کاملاً جدید و مستقل ایجاد کند. پس از ایجاد این نخ، متد `run()` درون آن و به صورت موازی با نخ اصلی اجرا خواهد شد.
-- Sequential vs Multithreaded Comparison:
- - Add a mode to simulate downloading chunks sequentially (one after another) and compare it with the multithreaded version.
- - Measure and report the total execution time of both approaches, and briefly analyze the difference in performance.
+### ۲. تفاوت رفتاری
+* **متد `start()`:** به صورت غیرهمگام (Asynchronous) عمل میکند. این متد با ایجاد یک Call Stack مجزا برای نخ جدید، امکان اجرای همزمان وظایف مختلف را فراهم میسازد.
+* **متد `run()`:** به صورت همگام (Synchronous) عمل میکند و رفتار آن کاملاً مشابه یک متد عادی است؛ در نتیجه، نخ فعلی را تا زمان اتمام اجرای کدهای خود متوقف (Block) میکند.
-## Evaluation ⚖️
+---
-Your work will be evaluated based on:
+## بخش دوم: نخهای پسزمینه (Daemon Threads)
-- **Thread Management**: Correct use of `start()` and `join()`.
-- **Simulation Logic**: Correct implementation of the loops and random delays in the worker threads.
-- **Thread Safety**: Following the constraint of each worker only writing to its own assigned object.
-- **Code Quality**: Readable code and proper use of Java conventions.
+### ۱. خروجی برنامه و دلیل آن
+* **خروجی:** معمولاً برنامه تنها با چاپ خط `Main thread ends.` پایان مییابد.
-**Total: 500 points**
-- 🧠 Theoretical Questions – 150 points
-- 💻 Practical Task (Download Manager) – 350 points
+**دلیل:** در جاوا، به محض اتمام کار تمامی نخهای کاربر (User Threads یا همان نخهای غیر دیمن)، ماشین مجازی جاوا (JVM) به طور خودکار بسته میشود. از آنجا که نخ `main` بلافاصله پس از فعالسازی نخ دیمن به پایان میرسد، JVM نیز کار برنامه را خاتمه میدهد و منتظر کامل شدن حلقه نخ دیمن نمیماند.
-## Submission ⌛
+### ۲. حذف خط `thread.setDaemon(true)`
+در صورت حذف این خط، نخ به یک نخ کاربر معمولی تبدیل میشود. در این حالت، حتی پس از اتمام کار نخ `main`، ماشین مجازی جاوا روشن باقی میماند و منتظر میشود تا این نخ تمام ۲۰ دور حلقه خود را (که حدود ۱۰ ثانیه زمان میبرد) به طور کامل اجرا کند.
-1. Add your mentor as a contributor to the project.
-2. Create a `develop` branch for implementing features.
-3. Use Git for regular code commits.
-4. Push your code and the answers file (Report.md) to the remote repository.
-5. Submit a pull request to merge the `develop` branch with `main`.
+### ۳. کاربردهای واقعی نخهای Daemon
+* **سیستم زبالهروبی جاوا (Garbage Collection):** مدیریت و آزادسازی حافظه بلااستفاده در پسزمینه برنامه.
+* **نخهای مانیتورینگ:** بررسی مداوم وضعیت سلامت و میزان مصرف منابع سیستم در پسزمینه.
+* **سیستم ذخیره خودکار (Auto-Save):** ذخیرهسازی دورهای اطلاعات در بازیها یا نرمافزارهای ویرایشگر، بدون ایجاد وقفه در جریان اصلی برنامه.
-**Deadline:** **Friday, June 5** (15th of Khordad)
+---
-## Additional Resources 📚
+## بخش سوم: روش کوتاهتر برای ساخت نخها (Lambda Expression)
-- [Java Concurrency and Multithreading](https://jenkov.com/tutorials/java-concurrency/index.html)
-- [Creating and Starting Java Threads](https://jenkov.com/tutorials/java-concurrency/creating-and-starting-threads.html)
-- [Thread.join() explained](https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#join--)
\ No newline at end of file
+### ۱. خروجی برنامه
+* **خروجی:** عبارت `Thread is running using a ...!` در کنسول چاپ میشود.
+
+### ۲. نام این سینتکس
+به سینتکس `() -> { ... }` اصطلاحاً **Lambda Expression** (عبارت لمبدا) میگویند.
+
+### ۳. تفاوت با روشهای سنتی
+در روشهای سنتی باید یک کلاس مجزا به صورت مشتقشده از `Thread` ایجاد میکردیم یا اینترفیس `Runnable` را از طریق یک کلاس جداگانه یا بینام (Anonymous Class) پیادهسازی مینمودیم. اما با استفاده از عبارت لمبدا، نیازی به نوشتن این کدهای تکراری و اضافی نیست و میتوان پیادهسازی تنها متد انتزاعی اینترفیس (یعنی متد `run`) را به صورت مستقیم و خلاصه به سازنده کلاس `Thread` پاس داد. این کار خوانایی کد را افزایش میدهد، در حالی که عملکرد آن در پشت صحنه هیچ تفاوتی با روشهای گذشته ندارد.
+
+
\ No newline at end of file
diff --git a/src/main/java/DownloadWorker.java b/src/main/java/DownloadWorker.java
index 546de2d..6be56e3 100644
--- a/src/main/java/DownloadWorker.java
+++ b/src/main/java/DownloadWorker.java
@@ -21,23 +21,40 @@ public class DownloadWorker implements Runnable {
@Override
public void run() {
- // TODO: Record the chunk start time in chunkStatus.
+ chunkStatus.setStartTimeMs(System.currentTimeMillis());
double downloaded = 0.0;
- // TODO: Print a message that this chunk has started downloading.
+ System.out.println("Worker for Chunk #" + chunkStatus.getChunkId() + " has started.");
while (downloaded < chunkStatus.getChunkSizeMB()) {
- // TODO: Generate a random sleep delay between min and max delay.
- // TODO: Sleep for that delay.
- // TODO: Generate a random download amount for this step.
- // TODO: Increase downloaded, but do not go beyond chunk size.
- // TODO: Save the updated downloaded value into chunkStatus.
- // TODO: Optionally print step-by-step progress.
+ // محاسبه زمان تاخیر تصادفی در محدوده مجاز کانفیگ
+ int delayRange = config.getMaxStepDelayMs() - config.getMinStepDelayMs();
+ int sleepDelay = config.getMinStepDelayMs() + (delayRange > 0 ? random.nextInt(delayRange + 1) : 0);
+
+ try {
+ Thread.sleep(sleepDelay);
+ } catch (InterruptedException e) {
+ System.out.println("Worker for Chunk #" + chunkStatus.getChunkId() + " was interrupted.");
+ return;
+ }
+
+ // محاسبه حجم دانلود تصادفی در این گام
+ double sizeRange = config.getMaxStepDownloadMB() - config.getMinStepDownloadMB();
+ double stepDownload = config.getMinStepDownloadMB() + (sizeRange > 0 ? random.nextDouble() * sizeRange : 0);
+
+ // اضافه کردن حجم دانلود شده بدون تجاوز از حجم کل چانک
+ downloaded += stepDownload;
+ if (downloaded > chunkStatus.getChunkSizeMB()) {
+ downloaded = chunkStatus.getChunkSizeMB();
+ }
+
+ chunkStatus.setDownloadedMB(downloaded);
}
- // TODO: Mark the chunk as completed.
- // TODO: Record the chunk end time in chunkStatus.
- // TODO: Print a message that this chunk has finished downloading.
+ chunkStatus.setCompleted(true);
+ chunkStatus.setEndTimeMs(System.currentTimeMillis());
+
+ System.out.println("Worker for Chunk #" + chunkStatus.getChunkId() + " has finished downloading.");
}
-}
+}
\ No newline at end of file
diff --git a/src/main/java/Main.java b/src/main/java/Main.java
index 82bd239..8aca790 100644
--- a/src/main/java/Main.java
+++ b/src/main/java/Main.java
@@ -34,48 +34,33 @@ public class Main {
workerThreads.add(workerThread);
- // TODO:
- // Students may print helpful debug information here,
- // for example which chunk is assigned to which worker thread.
+ // چاپ جزییات تخصیص چانک به نخها جهت دیباگ کردن برنامه
+ System.out.println("Assigned Chunk #" + chunk.getChunkId() + " (" + chunk.getChunkSizeMB() + " MB) to " + workerThread.getName());
}
// 4. Create and start monitor thread
ProgressMonitor monitor = new ProgressMonitor(config, chunks);
Thread monitorThread = new Thread(monitor, "Progress-Monitor");
- // TODO:
- // Start the monitor thread before starting the workers
- // so that progress can be displayed while downloading happens.
- //
- // Example idea:
- // monitorThread.start();
+ monitorThread.start();
// 5. Start worker threads
- // TODO:
- // Start each worker thread in workerThreads.
- // Use a loop and call start() on each thread.
+ for (Thread thread : workerThreads) {
+ thread.start();
+ }
// 6. Wait for workers to finish
- // TODO:
- // Wait for all worker threads to complete by calling join().
- // This should be done inside a try-catch block for InterruptedException.
- //
- // Hint:
- // for (Thread thread : workerThreads) {
- // thread.join();
- // }
+ try {
+ // انتظار برای به پایان رسیدن تک تک ورکرهای دانلود چانکها
+ for (Thread thread : workerThreads) {
+ thread.join();
+ }
- // TODO:
- // After all workers finish, the monitor thread may also need to stop.
- // Depending on how ProgressMonitor is implemented, students may:
- // - wait for it to finish on its own, or
- // - add a stopping mechanism in ProgressMonitor later.
- //
- // If your monitor finishes automatically, you may join it here.
-
- // NOTE:
- // this final report may show 0 progress because no worker has actually run yet.
- // Until students complete the thread start/join TODOs above,
+ // انتظار برای اتمام کار نخ مانیتور
+ monitorThread.join();
+ } catch (InterruptedException e) {
+ System.out.println("Main thread was interrupted while waiting for threads.");
+ }
// 7. Print final report
System.out.println();
@@ -104,4 +89,4 @@ public class Main {
System.out.println("Downloaded total: " + downloadedMB + "/" + config.getTotalSizeMB() + " MB");
System.out.println("Simulation finished.");
}
-}
+}
\ No newline at end of file
diff --git a/src/main/java/ProgressMonitor.java b/src/main/java/ProgressMonitor.java
index 475c0e0..8930d5a 100644
--- a/src/main/java/ProgressMonitor.java
+++ b/src/main/java/ProgressMonitor.java
@@ -16,17 +16,6 @@ public class ProgressMonitor implements Runnable {
@Override
public void run() {
- // TODO:
- // Repeatedly check chunk progress until all chunks are completed.
- // In each loop:
- // 1. Read the downloaded size from every chunk
- // 2. Add all downloaded amounts to totalDownloadedMB
- // 3. Count completed chunks
- // 4. Print a progress message
- // 5. If completedChunks == chunks.size(), print a final monitor message and stop
- // 6. Otherwise sleep for monitorDelayMs and continue
-
-
while (true) {
double totalDownloadedMB = 0.0;
int completedChunks = 0;
@@ -54,9 +43,11 @@ public class ProgressMonitor implements Runnable {
chunks.size()
);
-
- // TODO:
- // If all chunks are completed, print a final message and exit the loop
+ // بررسی پایان دانلود تمام چانکها برای خروج از حلقه مانیتور
+ if (completedChunks == chunks.size()) {
+ System.out.println("Progress Monitor: All chunks completed successfully. Exiting monitor thread.");
+ break;
+ }
try {
Thread.sleep(monitorDelayMs);
@@ -66,4 +57,4 @@ public class ProgressMonitor implements Runnable {
}
}
}
-}
+}
\ No newline at end of file