I have a thread exercise to record and read a text file in Java, but what I can't get is that the threads are synchronized. The way I have it, the threads interfere with each other, and when writing to the file, the thread for reading enters 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();
}
}
Used
synchronized
to synchronize method accesses.What this does is that if the recordFicheroTexto() method is being executed, then the object will be blocked so that it cannot be accessed within the block
synchronized
from another thread until it finishes, which will keep the execution synchronized.To achieve this, create a static variable that will be the semaphore between access to one method or another and you use it inside the block
synchronized(lock){ ... }
:It uses the aquire and release methods through a Semaphore object to block the reading thread if it is writing and vice versa.
OUTPUT