I really don't seem to pass this problem.
It appears there is a delay between incrementing a variable and stopping a thread
when the increment has been incrementet to count. It seems to run threads after
the main program is finished running.
Here are errors I received:
1. The run method must read words from the reader and add them to the result list.
2. After each string is read, the run method must increment readStringCount by 1.
3. The program should display the data read by each thread.
The program displayed too much data on the console (on the screen).
Perhaps someone can explain what is the problem with my code is?
package com.codegym.task.task16.task1628;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class Solution {
public static volatile AtomicInteger readStringCount = new AtomicInteger(0);
public static volatile BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
// Read string count
int count = Integer.parseInt(reader.readLine());
// Init threads
ReaderThread consoleReader1 = new ReaderThread();
ReaderThread consoleReader2 = new ReaderThread();
ReaderThread consoleReader3 = new ReaderThread();
consoleReader1.start();
consoleReader2.start();
consoleReader3.start();
while (count > readStringCount.get()) {
}
consoleReader1.interrupt();
consoleReader2.interrupt();
consoleReader3.interrupt();
System.out.println("#1:" + consoleReader1);
System.out.println("#2:" + consoleReader2);
System.out.println("#3:" + consoleReader3);
reader.close();
}
public static class ReaderThread extends Thread {
private List<String> result = new ArrayList<>();
public void run() {
//write your code here
while (!isInterrupted()) {
try {
result.add(reader.readLine());
readStringCount.incrementAndGet();
}
catch (IOException e) {
}
}
}
@Override
public String toString() {
return result.toString();
}
}
}