Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Challenge Executors | High-level Synchronization Mechanisms
Multithreading in Java
course content

Contenido del Curso

Multithreading in Java

Multithreading in Java

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

bookChallenge Executors

Task

Imagine that you have a list of files, each of which contains lines of text. Your task is to read lines from these files in parallel and count the number of words in each line. Use ExecutorService, Future, and a thread pool to accomplish the task.

Requirements:

  • Create a thread pool: Create a fixed-size thread pool using Executors.newFixedThreadPool(int nThreads), where nThreads is the number of threads in the pool;
  • Task Implementation: Implement a WordCountTask class that implements the Callable<String> interface and receives a file as input. In the call method of this class, read lines from the file, count the number of words in each line, and return the result;
  • Using ExecutorService: Using ExecutorService, send jobs to the thread pool for execution. The jobs must use the WordCountTask class.

Note

Also, the string that you form in a separate thread, you must return and use the get() method of the Future interface to get the result of the thread execution and output to the console in the main method.

Read from file

To implement the call() method, you can use BufferedReader to read strings from files. Employ a try-with-resources block so that resources are automatically closed for you.

java

Main

copy
1
BufferedReader reader = new BufferedReader(new FileReader(file));

Use the readLine() method to read each line, and be sure to check for null to determine when you've reached the end of the file.

Next, split the string into an array of strings using the split("\\s+") method with the \\s+ pattern, which separates the string by spaces, and then get the size of the array.

In the string itself, which the stream returns, use this formatting

java

Main

copy
1
String.format("File: %s | Line: %s | Word Count %d", fileName, line, countWord)

Files are already in the project you don't need to create or modify them!

Example output

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 3. Capítulo 7
We're sorry to hear that something went wrong. What happened?
some-alt