Skip to content

Instantly share code, notes, and snippets.

@ayu-24
Created October 15, 2019 08:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ayu-24/67c67730daa71b1e0ec4301e3f0f4813 to your computer and use it in GitHub Desktop.
Save ayu-24/67c67730daa71b1e0ec4301e3f0f4813 to your computer and use it in GitHub Desktop.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class Count implements Runnable {
private static long processedTime = 0;
File file;
public Count(File fileName) {
file = fileName;
}
public static void main(String[] args) throws InterruptedException {
File file = new File("/home/workspace/enwik8");
Runnable runnable = new Count(file);
long startTime = System.currentTimeMillis();
Thread thread;
for (int i = 0; i < 50; i++) {
thread =new Thread(runnable);
thread.start();
thread.join();
}
long elapsedTime = System.currentTimeMillis() - startTime;
System.out.println("Threads processing time " + elapsedTime + "milliseconds");
}
public void run() {
int i = 0;
int wordCount = 0;
try {
FileReader reader = new FileReader(file);
BufferedReader buffer = new BufferedReader(reader);
String line;
while ((line = buffer.readLine()) != null) {
String[] wordList = line.split(",");
wordCount += wordList.length;
}
System.out.println("Number of words in " + Thread.currentThread().getName() + "-" + wordCount);
reader.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}
@RostMyr
Copy link

RostMyr commented Mar 24, 2020

I might be wrong but you are not doing any work in parallel here. thread.join(); just blocks the current thread (main thread) waiting for the completion of the other thread (50 times). You should either use service executor or create all 50 threads, call start on them and add them to the list. Then you could iterate over this list and call method join.
https://docs.oracle.com/javase/tutorial/essential/concurrency/join.html

@ashvayka
Copy link

ashvayka commented Jun 2, 2020

@RostMyr is correct. This code is not executing tasks in parallel.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment