import java.io.FileWriter;
import java.io.IOException;

class Synchro {
    private FileWriter fileWriter;

    public Synchro(String file) throws IOException {
        fileWriter = new FileWriter(file, true);
    }
    public void close() {
        try {
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public synchronized void writing(String str, int i) {
        try {
            System.out.print(str + i);
            fileWriter.append(str + i);
            Thread.sleep((long)(Math.random() * 50));
            System.out.print("->" + i + " ");
            fileWriter.append("->" + i + " ");
        } catch (IOException ex) {
            System.out.print("Error of reading");
            ex.printStackTrace();
        } catch (InterruptedException e) {
            System.err.print("Error of stream");
            e.printStackTrace();
        }
    }
}

class MyThread extends Thread {
    private Synchro s;

    public MyThread(String str, Synchro s) {
        super(str);
        this.s = s;
    }
    public void run() {
        for (int i = 0; i < 5; i++) {
            s.writing(getName(), i);
        }
    }
}

public class SynchroThreads {
    public static void main(String[] args) {
        try {
            Synchro s = new Synchro("C:\\Users\\~\\Downloads\\data.txt");

            MyThread t1 = new MyThread("First", s);
            MyThread t2 = new MyThread("Second", s);
            t1.start();
            t2.start();
            t1.join();
            t2.join();
            s.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
