Есть два потока.
1) Выполняет считывание символов из файла
2) Проверяет является ли символ числом, если нет кидает эксепшен
Не могу понять каким образом сделать так что бы гарантированно первым запускался поток считывания из файла и не могу сообразить какое условие задать в цикле второго потока, что бы он завершался вместе с первым если символы в файле закончились. Заранее спасибо за любую помощь.
public class MultiThread {
private static Object monitor = new Object();
public static void main(String[] args) {
ReadFromFile readFromFile = new ReadFromFile("MultiThreaded\\MultithreadingMatrix\\matrixA.txt");
Thread readFromFileThread = new Thread(readFromFile);
Thread validationThread = new Thread(new Validation());
try {
readFromFileThread.start();
validationThread.start();
readFromFileThread.join();
validationThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static class ReadFromFile implements Runnable {
private String path;
private StringBuilder matrix;
private static Character character;
public ReadFromFile(String path) {
this.path = path;
this.matrix = new StringBuilder();
}
@Override
public void run() {
System.out.println(" Read from file start ");
try (InputStreamReader isr = new InputStreamReader(ClassLoader.getSystemResourceAsStream(path))) {
while (isr.ready()) {
synchronized (monitor) {
character = (char) isr.read();
matrix.append(character);
monitor.notify();
monitor.wait();
}
}
} catch (InterruptedException | IOException e) {
e.printStackTrace();
}
System.out.println(" Read from file end ");
}
}
private static class Validation implements Runnable {
private Character currentChar;
@Override
public void run() {
System.out.println(" Validation start ");
try {
while (true) {
synchronized (monitor) {
currentChar = ReadFromFile.character;
if (currentChar != null) {
if (currentChar != ' ' && currentChar != '\n' && currentChar != '\r'
&& currentChar != '-') {
if (!Character.isDigit(currentChar)) {
throw new ValidationException();
} else {
System.out.println(currentChar + " число");
}
}
}
monitor.notify();
monitor.wait();
}
}
} catch (InterruptedException | ValidationException e) {
e.printStackTrace();
}
System.out.println(" Validation end ");
}
}
}
run
первого потока