I have an exercise of threads to record and read a text file in Java, but what I do not get is that the threads are synchronized. In the way I have it, the threads interfere with each other, and at the time of writing in the file the thread for reading comes into play at the same time. How could I synchronize the threads in the code I have? Thanks in advance.
Code:
public class Ejercicio7 extends Thread
{
public static void main(String[] args)
{
Thread hilo1 = new Ejercicio7(); hilo1.setName("hilo1");
Thread hilo2 = new Ejercicio7(); hilo2.setName("hilo2");
hilo1.start();
hilo2.start();
}
public void run()
{
if(Thread.currentThread().getName().equals("hilo1"))
{
grabarFicheroTexto();
}
else
{
try {
leerFicheroTexto();
} catch (IOException e) {e.printStackTrace();}
}
}
public static void grabarFicheroTexto()
{
char c;
try{
System.out.println("Vas a escribir en un fichero de texto en Java\n");
System.out.print("Escribe aqui: ");
FileWriter fichero=new FileWriter("..\Threads\src\ejercicio7\Archivo.txt");
StringBuffer str=new StringBuffer();
while ((c=(char)System.in.read())!='\n')
str.append(c);
String cadena=new String(str);
fichero.write(cadena);
if (fichero!=null)
fichero.close();
}catch(IOException ex){}
System.out.println("FICHERO ESCRITO CORRECTAMENTE");
}
public static void leerFicheroTexto()throws IOException
{
System.out.println("Estas leyendo un fichero de texto en Java\n");
FileReader fr = new FileReader("..\Threads\src\ejercicio7\Archivo.txt");
BufferedReader br = new BufferedReader(fr);
String s;
while((s = br.readLine()) != null) {
System.out.println(s);
}
fr.close();
}
}