Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Multithreading Task | Multithreading Basics
Multithreading in Java
course content

Зміст курсу

Multithreading in Java

Multithreading in Java

1. Multithreading Basics
2. Synchronized Collections
3. High-level Synchronization Mechanisms
4. Multithreading Best Practices

book
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

  1. 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).

  2. 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.

  3. Start the threads: Once each thread is created, initiate it by calling the start() method.

  4. 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.

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 1. Розділ 7
We're sorry to hear that something went wrong. What happened?
some-alt