There are two streams.
1) Reads characters from a file.
2) Checks if a character is a number, if not throws an ekpepshen
I can’t understand how to make sure that the first read stream from the file starts up, and I can’t figure out what condition to set in the second thread loop, so that it ends with the first one if the characters in the file are over. Thanks in advance for any help.
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 "); } } }
runfirst thread - iksuy Nov.