我有一个线程练习来记录和读取 Java 中的文本文件,但我无法得到线程是同步的。我有它的方式,线程相互干扰,并且在写入文件时,读取线程同时进入。如何同步我拥有的代码中的线程?提前致谢。
代码:
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();
}
}
用于
synchronized
同步方法访问。这样做的作用是,如果正在执行 recordFicheroTexto() 方法,则该对象将被阻塞,以便在
synchronized
完成之前无法从另一个线程在该块内访问它,这将保持执行同步。为此,请创建一个静态变量,该变量将成为访问一种或另一种方法之间的信号量,并在块内使用它
synchronized(lock){ ... }
:它通过 Semaphore 对象使用 aquire 和 release 方法来阻止正在写入的读取线程,反之亦然。
输出