Conteúdo do Curso
Multithreading in Java
Multithreading in Java
Challenge 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)
, wherenThreads
is the number of threads in the pool; -
Task Implementation: Implement a
WordCountTask
class that implements theCallable<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
: UsingExecutorService
, send jobs to the thread pool for execution. The jobs must use theWordCountTask
class.
Note
Also, the string that you form in a separate thread, you must return and use the
get()
method of theFuture
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.
Main
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
Main
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
Obrigado pelo seu feedback!