The first thread determines the number of spaces in the file, if the number of spaces is even - the second stream capitalizes the first letters of all words in the file, if odd - the last letters. With the wait and notify.Something is wrong with wait and notify, creates a short circuit and it does not work.
public class Dispatcher {
public static void main(String[] args) {
FileHandler fileHandler = new FileHandler();
Thread thread = new CountSpaces(new File("text.txt"), fileHandler);
Thread thread1 = new ChangeText(new File("text.txt"), fileHandler);
thread.start();
thread1.start();
}
}
class CountSpaces extends Thread{
File file;
FileHandler fileHandler;
public CountSpaces(File file, FileHandler fileHandler) {
this.file = file;
this.fileHandler = fileHandler;
}
@Override
public void run() {
fileHandler.countSpace(file);
}
}
class ChangeText extends Thread {
File file;
FileHandler fileHandler;
public ChangeText(File file, FileHandler fileHandler) {
this.file = file;
this.fileHandler = fileHandler;
}
@Override
public void run() {
try {
fileHandler.changeLetters(file);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class FileHandler {
boolean flag = false;
int count;
void countSpace(File file) {
try (Scanner sc = new Scanner(file)) {
synchronized (this){
wait();
while (sc.hasNext() && !flag) {
count++;
sc.next();
}
flag = true;
notify();
}
} catch (Exception e) {
e.printStackTrace();
}
}
void changeLetters(File file) throws InterruptedException {
try (Scanner sc = new Scanner(file);
PrintWriter printWriter = new PrintWriter(file + "result")) {
synchronized (this){
wait();
if (count % 2 == 0) {
while (sc.hasNext() && flag) {
String word = sc.next();
printWriter.print(word.substring(0, 1).toUpperCase() + word.substring(1));
}
} else {
while (sc.hasNext() && flag) {
String word = sc.next();
printWriter.print(word.substring(1, word.length() - 1)
+ word.substring(word.length() - 1).toUpperCase());
}
}
flag = false;
notify();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}