I'm trying to make a program write to a file using the RandomAccessFile class in a parallel and mutually exclusive way.
When compiling and executing works, the problem comes when, when I open the file, I see that the letters are in order but that some letters are not and only leave a space.
public class ficheroSeguro extends Thread implements Runnable{
//macro para el fichero
static final String MiArchivo =
"C:/Users/Raul_/Desktop/PCTR 7/ficheroSeguroTexto.txt";
//cadena que pasamos al constructor
static String palabrasfichero;
//contador para ver el orden en que se ejecutan
int i;
public ficheroSeguro(String S,int i){
this.palabrasfichero = S;
this.i=i;
}
public synchronized void run(){
long threadId = ficheroSeguro.currentThread().getId();
System.out.println("Ejecutando el hilo: " +threadId+ "con valor: " +i);
try{
writeData(MiArchivo,palabrasfichero,i);
}catch(IOException e){System.out.println("Error en metodo run");}
}
public static void writeData(String S, String data, int i) throws IOException {
RandomAccessFile raf1 = new RandomAccessFile(MiArchivo, "rw");
raf1.seek(i);
raf1.writeChar(palabrasfichero.charAt(i));
raf1.close();
}
public static void main(String[] args) throws InterruptedException{
Scanner sc = new Scanner(System.in);
try{
RandomAccessFile raf = new RandomAccessFile (MiArchivo,"rw");
raf.setLength(0);
} catch(FileNotFoundException e){System.out.println("Error al abrir");}
catch(IOException e){System.out.println("Error al vaciar");}
String cadena = sc.next();
//ejecutor con tantos hilos como tamaño tenga la cadena
ExecutorService exe= Executors.newFixedThreadPool(cadena.length());
for(int i = 0; i<cadena.length();i++){
exe.execute(new ficheroSeguro(cadena,i));
}
exe.shutdown();
exe.awaitTermination(10, TimeUnit.MILLISECONDS);
}
}'
When I execute it and print on the screen the system.out of the run, the threads appear with a different order
Ejecutando el hilo: 14con valor: 1
Ejecutando el hilo: 12con valor: 0
Ejecutando el hilo: 16con valor: 2
Ejecutando el hilo: 18con valor: 3