From 16f863e48b0850d0e3c4f3f5287c68e7421c05ca Mon Sep 17 00:00:00 2001 From: ermiababaie Date: Fri, 10 May 2024 15:46:46 +0330 Subject: [PATCH 1/3] first commit(matrix and task complated) --- .../java/sbu/cs/MatrixMultiplication.java | 97 ++++++++++++++++--- src/main/java/sbu/cs/TaskScheduler.java | 42 +++++--- 2 files changed, 111 insertions(+), 28 deletions(-) diff --git a/src/main/java/sbu/cs/MatrixMultiplication.java b/src/main/java/sbu/cs/MatrixMultiplication.java index 2f00c59..902cc96 100644 --- a/src/main/java/sbu/cs/MatrixMultiplication.java +++ b/src/main/java/sbu/cs/MatrixMultiplication.java @@ -1,5 +1,6 @@ package sbu.cs; +import java.util.ArrayList; import java.util.List; public class MatrixMultiplication { @@ -8,16 +9,40 @@ public class MatrixMultiplication { public static class BlockMultiplier implements Runnable { List> tempMatrixProduct; - public BlockMultiplier() { - // TODO + int num; + List> matrix_A, matrix_B; + public BlockMultiplier(int num, List> matrix_A, List> matrix_B) { + this.num = num; + this.matrix_A = matrix_A; + this.matrix_B = matrix_B; + tempMatrixProduct = new ArrayList<>(); } @Override public void run() { - /* - TODO - Perform the calculation and store the final values in tempMatrixProduct - */ + int x = 0, y = 0; + int p, q, r; + p = matrix_A.size(); + q = matrix_B.size(); + r = matrix_B.get(0).size(); + if (num == 2 || num == 4) + y = r / 2; + if (num == 3 || num == 4) + x = p / 2; + for (int i = 0; i < p / 2; i++) { + List satr = new ArrayList<>(); + for (int j = 0; j < r / 2; j++) { + int ans = 0; + for (int k = 0; k < q; k++) { + ans += matrix_A.get(x + i).get(k) * matrix_B.get(k).get(y + j); + } + satr.add(ans); + } + tempMatrixProduct.add(satr); + } + } + public List> getTempMatrixProduct() { + return tempMatrixProduct; } } @@ -28,16 +53,60 @@ public void run() { */ public static List> ParallelizeMatMul(List> matrix_A, List> matrix_B) { - /* - TODO - Parallelize the matrix multiplication by dividing tasks between 4 threads. - Each thread should calculate one block of the final matrix product. Each block should be a quarter of the final matrix. - Combine the 4 resulting blocks to create the final matrix product and return it. - */ - return null; + List> ParallelizeMatMul = new ArrayList<>(); + + List> mat1 = new ArrayList<>(); + List> mat2 = new ArrayList<>(); + List> mat3 = new ArrayList<>(); + List> mat4 = new ArrayList<>(); + + BlockMultiplier BM1 = new BlockMultiplier(1, matrix_A, matrix_B); + BlockMultiplier BM2 = new BlockMultiplier(2, matrix_A, matrix_B); + BlockMultiplier BM3 = new BlockMultiplier(3, matrix_A, matrix_B); + BlockMultiplier BM4 = new BlockMultiplier(4, matrix_A, matrix_B); + + Thread thread1 = new Thread(BM1); + Thread thread2 = new Thread(BM2); + Thread thread3 = new Thread(BM3); + Thread thread4 = new Thread(BM4); + + thread1.start(); + thread2.start(); + thread3.start(); + thread4.start(); + + try { + thread1.join(); + mat1 = BM1.getTempMatrixProduct(); + thread2.join(); + mat2 = BM2.getTempMatrixProduct(); + thread3.join(); + mat3 = BM3.getTempMatrixProduct(); + thread4.join(); + mat4 = BM4.getTempMatrixProduct(); + }catch (InterruptedException e) { + System.out.println("thread Interrupted."); + } + for (int i = 0; i < mat1.size(); i++) { + List satr = new ArrayList<>(); + for (int j = 0; j < mat1.get(0).size(); j++) + satr.add(mat1.get(i).get(j)); + for (int j = 0; j < mat2.get(0).size(); j++) + satr.add(mat2.get(i).get(j)); + ParallelizeMatMul.add(satr); + } + for (int i = 0; i < mat3.size(); i++) { + List satr = new ArrayList<>(); + for (int j = 0; j < mat3.get(0).size(); j++) + satr.add(mat3.get(i).get(j)); + for (int j = 0; j < mat4.get(0).size(); j++) + satr.add(mat4.get(i).get(j)); + ParallelizeMatMul.add(satr); + } + return ParallelizeMatMul; } public static void main(String[] args) { - // Test your code here + } } diff --git a/src/main/java/sbu/cs/TaskScheduler.java b/src/main/java/sbu/cs/TaskScheduler.java index 8725c2a..4753719 100644 --- a/src/main/java/sbu/cs/TaskScheduler.java +++ b/src/main/java/sbu/cs/TaskScheduler.java @@ -1,6 +1,7 @@ package sbu.cs; import java.util.ArrayList; +import java.util.Collection; import java.util.List; public class TaskScheduler @@ -12,7 +13,6 @@ public static class Task implements Runnable */ String taskName; int processingTime; - public Task(String taskName, int processingTime) { this.taskName = taskName; this.processingTime = processingTime; @@ -23,29 +23,43 @@ public Task(String taskName, int processingTime) { @Override public void run() { - /* - TODO - Simulate utilizing CPU by sleeping the thread for the specified processingTime - */ + try { + Thread.sleep(processingTime); + } catch (InterruptedException e) { + System.out.println("thread Interrupted."); + } + } } public static ArrayList doTasks(ArrayList tasks) { ArrayList finishedTasks = new ArrayList<>(); - - /* - TODO - Create a thread for each given task, And then start them based on which task has the highest priority - (highest priority belongs to the tasks that take more time to be completed). - You have to wait for each task to get done and then start the next task. - Don't forget to add each task's name to the finishedTasks after it's completely finished. - */ + for (int i = 1; i < tasks.size(); i++) { + int j = i; + while (j > 0 && tasks.get(j).processingTime > tasks.get(j - 1).processingTime) { + Task save = tasks.get(j); + tasks.set(j, tasks.get(j - 1)); + tasks.set(j - 1, save); + j--; + } + } + for (Task t: tasks) { + finishedTasks.add(t.taskName); + } + for (Task i: tasks) { + Thread thread = new Thread(i); + thread.start(); + try { + thread.join(); + } catch (InterruptedException e) { + System.out.println("Interrupted."); + } + } return finishedTasks; } public static void main(String[] args) { - // Test your code here } } From 9ae6733b4296f8ea6f0e06664d312e922cc9697b Mon Sep 17 00:00:00 2001 From: ermia babaie <160699260+ermiababaie@users.noreply.github.com> Date: Fri, 10 May 2024 15:49:21 +0330 Subject: [PATCH 2/3] Add files via upload --- answer.md | 150 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 150 insertions(+) create mode 100644 answer.md diff --git a/answer.md b/answer.md new file mode 100644 index 0000000..d69deb2 --- /dev/null +++ b/answer.md @@ -0,0 +1,150 @@ +# Fifth-Assignment-Multithread-Basics + +## Table of contents + +- [Introduction 👋](#introduction-) +- [Objectives 🎯](#objectives-) +- [Tasks 📋](#tasks-) + - [Theoretical Questions 📝](#theoretical-questions-) + - [Practical Questions 💻](#practical-questions-) +- [Evaluation ⚖️](#evaluation-) +- [Submission ⌛](#submission-) +- [Resources 📚](#resources-) + +## Introduction 👋 + +Welcome to your Fifth Advanced Programming (AP) journey, where you'll delve into the fascinating world of multithreading in Java. This project is divided into two main sections: + +1. **Theoretical Questions**: This section is designed to deepen your understanding of key multithreading concepts in Java. You'll have to analyze three code blocks and answer questions about them. + +2. **Practical Questions**: In this section, you'll get hands-on experience with multithreading in Java. Test cases are provided for each problem, but your code will still be manually checked to ensure you've implemented + + +## Objectives 🎯 + +By completing this assignment, you will: + +- Deepen your understanding of **multithreading** in Java and apply the concepts effectively. +- Gain familiarity with key multithreading concepts such as the `Runnable` interface, the `Thread` class, the `interrupt()` method, and the `run()` method. + +Note that while this assignment covers many important aspects of multithreading, there are some advanced topics such as race condition and synchronization that won't be covered in this assignment and will be introduced in the following week. However, a solid understanding of the concepts covered in this assignment is crucial for grasping those advanced topics. + +## Tasks 📋 + +### Theoretical Questions 📝 + +**Note: Please answer these questions in a Markdown file and place it in the root directory of your fork. Include code or screenshots where you see fit.** + +1. **What will be printed after interrupting the thread?** + +```java +public static class SleepThread extends Thread { + public void run() { + try { + Thread.sleep(10000); + } catch (InterruptedException e) { + System.out.println("Thread was interrupted!"); + } finally { + System.out.println("Thread will be finished here!!!"); + } + } + } + + public static void main(String[] args) { + SleepThread thread = new SleepThread(); + thread.start(); + thread.interrupt(); + } +``` +2. In Java, what would be the outcome if the `run()` method of a `Runnable` object is invoked directly, without initiating it inside a `Thread` object? +```java +public class DirectRunnable implements Runnable { + public void run() { + System.out.println("Running in: " + Thread.currentThread().getName()); + } +} + +public class Main { + public static void main(String[] args) { + DirectRunnable runnable = new DirectRunnable(); + runnable.run(); + } +} +``` +3. Elaborate on the sequence of events that occur when the `join()` method of a thread (let's call it `Thread_0`) is invoked within the `Main()` method of a Java program. +```java +public class JoinThread extends Thread { + public void run() { + System.out.println("Running in: " + Thread.currentThread().getName()); + } +} + +public class Main { + public static void main(String[] args) { + JoinThread thread = new JoinThread(); + thread.start(); + try { + thread.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println("Back to: " + Thread.currentThread().getName()); + } +} +``` + +### Practical Questions 💻 + +**Task Scheduler**: + +- In this problem, you are given an **ArrayList** of tasks, each with two fields: **taskName** and **processingTime**. The goal is to sort these tasks based on their priority, where tasks with longer processing times have higher priority. After sorting, we’ll create separate threads for each task and execute them. Importantly, we’ll wait for each thread to finish its work to ensure the desired execution order. Finally, we’ll return the order of task execution. + +**Parallelizing Matrix Multiplication**: + +- In this problem, you are asked to write a program that can parallelize matrix multiplication using multithreading. + +- In the **ParallelizeMatMul** method, you will be given two matrices, **A** and **B**. Matrix **A** has dimensions **p** × **q**, and matrix **B** has dimensions **q** × **r** (where both **p** and **r** are even numbers). Your task is to compute the product of matrices **A** and **B** to obtain a resulting matrix, **C**. To achieve faster execution, we’ll utilize multithreading. + +- **Hint**: + - Divide the final matrix **C** into four equal quarters, as shown in the figure below. Assign each quarter to a separate thread for calculations. + + ![](./Images/OIG3.jpeg) + + - Procedure: + 1. Divide the quarters among four threads in the **ParallelizeMatMul** method. + 2. Specify how each thread should calculate the elements in its assigned quarter within its **run()** method. + 3. Store the calculated elements from each thread in temporary matrices. + 4. Combine the temporary matrices to construct the final matrix **C**. + + +## Evaluation ⚖️ + +Your work on this assignment will be evaluated based on: + +- **Understanding of Multithreading Concepts**: Your ability to accurately answer the theoretical questions, demonstrating a deep understanding of multithreading in Java. Remember that the answers to the theoretical questions should be provided separately in a markdown file. + +- **Test Cases**: Your code should pass all the tests provided in the test directory. Make sure to enable GitHub Actions to run the tests on GitHub. + +- **Code Quality**: Your code should be well-structured, readable, and efficient. Proper use of Java conventions, including variable naming, class structure, and comments, will also be considered. + +## Submission ⌛ + +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 to the remote repository. +5. Submit a pull request to merge the `develop` branch with `main`. + +The deadline for submitting your code is **Wednesday, May 8** (19th of Ordibehesht) + +## Resources 📚 + +For assistance with this assignment, you may refer to the following resources: + +🔗 [Multithreading in Java on Java Point](https://www.javatpoint.com/multithreading-in-java) + +🔗 [Multithreading in Java on Tutorials Point](https://www.tutorialspoint.com/java/java_multithreading.htm) + +🔗 [Multithreading in Java on Geeks for Geeks](https://www.geeksforgeeks.org/multithreading-in-java/) + +Also, you can find a wealth of knowledge from various YouTube courses. They can be a great source of learning. Alongside, joining discussions on forums and reading helpful documents can also be beneficial. From 547397b46f3489ff19960c1266cd97f8154d18b1 Mon Sep 17 00:00:00 2001 From: ermia babaie <160699260+ermiababaie@users.noreply.github.com> Date: Fri, 10 May 2024 17:27:09 +0330 Subject: [PATCH 3/3] Update answer.md --- answer.md | 157 +++++++----------------------------------------------- 1 file changed, 18 insertions(+), 139 deletions(-) diff --git a/answer.md b/answer.md index d69deb2..b694c0e 100644 --- a/answer.md +++ b/answer.md @@ -1,150 +1,29 @@ -# Fifth-Assignment-Multithread-Basics +# Fifth-Assignment-Multithread Theoretical Questions 📝 answers -## Table of contents +## Question 1: -- [Introduction 👋](#introduction-) -- [Objectives 🎯](#objectives-) -- [Tasks 📋](#tasks-) - - [Theoretical Questions 📝](#theoretical-questions-) - - [Practical Questions 💻](#practical-questions-) -- [Evaluation ⚖️](#evaluation-) -- [Submission ⌛](#submission-) -- [Resources 📚](#resources-) +1. interrupt() method: If any thread is in sleeping or waiting for a state then using the interrupt() method, we can interrupt the execution of that thread by showing InterruptedException. A thread that is in the sleeping or waiting state can be interrupted with the help of the interrupt() method of Thread class. -## Introduction 👋 +2. in this code sleep get ignored and thread work without sleep. +### outPut: +Thread was interrupted! -Welcome to your Fifth Advanced Programming (AP) journey, where you'll delve into the fascinating world of multithreading in Java. This project is divided into two main sections: +Thread will be finished here!!! -1. **Theoretical Questions**: This section is designed to deepen your understanding of key multithreading concepts in Java. You'll have to analyze three code blocks and answer questions about them. -2. **Practical Questions**: In this section, you'll get hands-on experience with multithreading in Java. Test cases are provided for each problem, but your code will still be manually checked to ensure you've implemented +## Question 2: +1. the run() method is called directly, so the message will be printed from the main thread +2. run() in this code exactly worked like function +3. code running step by step +### outPut: +Running in main -## Objectives 🎯 +## Question 3: +1. The join method allows one thread to wait for the completion of another. If t is a Thread object whose thread is currently executing, t. join(); causes the current thread to pause execution until t 's thread terminates. -By completing this assignment, you will: +### outPut: +Running in: Thread-0 -- Deepen your understanding of **multithreading** in Java and apply the concepts effectively. -- Gain familiarity with key multithreading concepts such as the `Runnable` interface, the `Thread` class, the `interrupt()` method, and the `run()` method. +Back to: main -Note that while this assignment covers many important aspects of multithreading, there are some advanced topics such as race condition and synchronization that won't be covered in this assignment and will be introduced in the following week. However, a solid understanding of the concepts covered in this assignment is crucial for grasping those advanced topics. - -## Tasks 📋 - -### Theoretical Questions 📝 - -**Note: Please answer these questions in a Markdown file and place it in the root directory of your fork. Include code or screenshots where you see fit.** - -1. **What will be printed after interrupting the thread?** - -```java -public static class SleepThread extends Thread { - public void run() { - try { - Thread.sleep(10000); - } catch (InterruptedException e) { - System.out.println("Thread was interrupted!"); - } finally { - System.out.println("Thread will be finished here!!!"); - } - } - } - - public static void main(String[] args) { - SleepThread thread = new SleepThread(); - thread.start(); - thread.interrupt(); - } -``` -2. In Java, what would be the outcome if the `run()` method of a `Runnable` object is invoked directly, without initiating it inside a `Thread` object? -```java -public class DirectRunnable implements Runnable { - public void run() { - System.out.println("Running in: " + Thread.currentThread().getName()); - } -} - -public class Main { - public static void main(String[] args) { - DirectRunnable runnable = new DirectRunnable(); - runnable.run(); - } -} -``` -3. Elaborate on the sequence of events that occur when the `join()` method of a thread (let's call it `Thread_0`) is invoked within the `Main()` method of a Java program. -```java -public class JoinThread extends Thread { - public void run() { - System.out.println("Running in: " + Thread.currentThread().getName()); - } -} - -public class Main { - public static void main(String[] args) { - JoinThread thread = new JoinThread(); - thread.start(); - try { - thread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - System.out.println("Back to: " + Thread.currentThread().getName()); - } -} -``` - -### Practical Questions 💻 - -**Task Scheduler**: - -- In this problem, you are given an **ArrayList** of tasks, each with two fields: **taskName** and **processingTime**. The goal is to sort these tasks based on their priority, where tasks with longer processing times have higher priority. After sorting, we’ll create separate threads for each task and execute them. Importantly, we’ll wait for each thread to finish its work to ensure the desired execution order. Finally, we’ll return the order of task execution. - -**Parallelizing Matrix Multiplication**: - -- In this problem, you are asked to write a program that can parallelize matrix multiplication using multithreading. - -- In the **ParallelizeMatMul** method, you will be given two matrices, **A** and **B**. Matrix **A** has dimensions **p** × **q**, and matrix **B** has dimensions **q** × **r** (where both **p** and **r** are even numbers). Your task is to compute the product of matrices **A** and **B** to obtain a resulting matrix, **C**. To achieve faster execution, we’ll utilize multithreading. - -- **Hint**: - - Divide the final matrix **C** into four equal quarters, as shown in the figure below. Assign each quarter to a separate thread for calculations. - - ![](./Images/OIG3.jpeg) - - - Procedure: - 1. Divide the quarters among four threads in the **ParallelizeMatMul** method. - 2. Specify how each thread should calculate the elements in its assigned quarter within its **run()** method. - 3. Store the calculated elements from each thread in temporary matrices. - 4. Combine the temporary matrices to construct the final matrix **C**. - - -## Evaluation ⚖️ - -Your work on this assignment will be evaluated based on: - -- **Understanding of Multithreading Concepts**: Your ability to accurately answer the theoretical questions, demonstrating a deep understanding of multithreading in Java. Remember that the answers to the theoretical questions should be provided separately in a markdown file. - -- **Test Cases**: Your code should pass all the tests provided in the test directory. Make sure to enable GitHub Actions to run the tests on GitHub. - -- **Code Quality**: Your code should be well-structured, readable, and efficient. Proper use of Java conventions, including variable naming, class structure, and comments, will also be considered. - -## Submission ⌛ - -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 to the remote repository. -5. Submit a pull request to merge the `develop` branch with `main`. - -The deadline for submitting your code is **Wednesday, May 8** (19th of Ordibehesht) - -## Resources 📚 - -For assistance with this assignment, you may refer to the following resources: - -🔗 [Multithreading in Java on Java Point](https://www.javatpoint.com/multithreading-in-java) - -🔗 [Multithreading in Java on Tutorials Point](https://www.tutorialspoint.com/java/java_multithreading.htm) - -🔗 [Multithreading in Java on Geeks for Geeks](https://www.geeksforgeeks.org/multithreading-in-java/) - -Also, you can find a wealth of knowledge from various YouTube courses. They can be a great source of learning. Alongside, joining discussions on forums and reading helpful documents can also be beneficial.