Hi there,
after I tried everything for hours, I still haven't a result. I am not capable to close the reader in time.
It still needs more entries in the console.
That's my code now in the run method:
public void run() {
//schreib hier deinen Code
while (true) {
if (isInterrupted()) {
System.out.println("Ich bin fertig");
return;
}
if (!isInterrupted()) {
try {
String zeile = reader.readLine();
if (!zeile.isEmpty()) {
result.add(zeile);
readStringCount.getAndIncrement();
}
} catch (IOException e) {
}
}
}
}
@Override
public String toString () {
return result.toString();
}
}
}
and that's my output:
4
ee
r
f
d
#1:[ee]
#2:[d]
#3:[r, f]
Ich bin fertig
Ich bin fertig
Ich bin fertig
Process finished with exit code 0
As you can see, there is no automatic closure of the reader or shutdown of the Thread, when it is interrupted. It needs two more entries in the console. Can anybody explain to me, why? Thanks Claudia
package de.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 {
// Zeichenkette für count lesen
int count = Integer.parseInt(reader.readLine());
// Threads initialisieren
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() {
//schreib hier deinen Code
while (!Thread.currentThread().isInterrupted()){
try {
String zeile = reader.readLine();
result.add(zeile);
readStringCount.getAndIncrement();
} catch (IOException e) {
break;
}
}
}
@Override
public String toString() {
return result.toString();
}
}
}