Mam taki kawałek kodu. Mam wątek główny który tworzy trzy wątki podrzędne, czy pętla która jest zadeklarowana z warunkiem count > readStringCount.get w wątku głównym zapętla ten wątek główny ? który czeka na to aż wątek podrzędny który korzysta ze pola volatile BufferedReadera? wykona akcje wprowadzenia ciągu przez użytkownika do konsoli? Rozumiem mniej więcej samo działanie słowa kluczowego volatile, ale chciałbym wiedzieć czy dobrze myślę.
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 {
int count = Integer.parseInt(reader.readLine());
// Inicjuje wątki
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 (true) {
try {
String s;
if ((s = reader.readLine ()) != null) {
readStringCount.getAndIncrement ();
result.add (s);
}
} catch (IOException e) {
throw new RuntimeException (e);
}
}
}
@Override
public String toString() {
return result.toString();
}
}
}