I've written this code, it meets all the requirements except the very first one:
The run method must run until the thread is terminated (!IsInterrupted).
I thought the following while-loop in the run() method was serving that purpose:
public void run() {
while (!isInterrupted()) {...}
}
Besides, IntellijIDEA produces no output, whereas the output on CodeGym's server is the following:
#1:[1, 2, 3, 4, 5, ]
#2:[]
#3:[]
Exception in thread "Thread-2" java.lang.NullPointerException at com.codegym.task.task16.task1628.Solution$ReaderThread.run(Solution.java:49)
Exception in thread "Thread-3" java.lang.NullPointerException at com.codegym.task.task16.task1628.Solution$ReaderThread.run(Solution.java:49)
That probably means that the 2nd and 3d threads (consoleReader2 and consoleReader3) haven't been filled with values. They probably got interrupted too early. I'm not sure how to fix that and how to make the program first let every thread finish its work and only then stop. I thought the run method completed the whole cycle for each thread...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() {
while (!isInterrupted()) {
try {
String s = null;
s = reader.readLine();
if (!s.equals(null)) {
result.add(s);
readStringCount.incrementAndGet();
}
} catch (IOException e) {
//e.printStackTrace();
}
}
}
@Override
public String toString() {
return result.toString();
}
}
}