Зміст курсу
Multithreading in Java
Multithreading in Java
Multithreading Task
Task
You need to write logic to create 100 threads, each of which will calculate the factorial of the index in a loop and save the result to the results
array.
You also need to wait for all threads to complete before outputting the results. (join()
method)
The methods factorial()
, printMassive()
, getResults()
are ready-made and you don't need to modify them in any way
factorial(Integer)
- calculates the factorial of the number you passed in;
printMassive(BigInteger[])
- prints the results array to the console;
getResults()
- gives the results array (used for tests);
SIZE_MASSIVE
- constant for defining the array value (DO NOT CHANGE);
results[]
- array for recording results.
Once you've done the task, go to src/test/java/TaskThreadTest.java
and run it
You should only have one test to pass the first time you run it
When you do the task correctly all the tests should pass, if some test does not pass, then you have implemented calculateFactorialsInParallel()
incorrectly or changed those fields/methods that cannot be changed
Implementation Plan
-
Create an array of threads: Set up an array of
Thread
objects, where each element corresponds to a different thread. The array's size should match the array you're processing (SIZE_MASSIVE = 100
). -
Initialize each thread: In a loop that iterates through each element of the array, create a new thread. Within this thread, perform the required task (calculate the factorial of the index). Store the result in the results array.
-
Start the threads: Once each thread is created, initiate it by calling the
start()
method. -
Wait for all threads to complete: After starting all threads, use the
join()
method on each thread to ensure that the main program thread waits for all threads to finish. This guarantees that all calculations are complete before the main program thread proceeds.
Дякуємо за ваш відгук!