The threads of my executor are not executed in order

0

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
    
asked by Resco 28.11.2017 в 19:05
source

1 answer

0

If you run your program several times, you will probably notice that the order in which the threads run varies each time. This is 100% normal!

When you run multiple threads in parallel, there is no guarantee as to the order in which they will run. In fact, it is even possible that thread A starts running before thread B , but thread B terminates its execution before thread A . All this depends entirely on how the operating system assigns CPU time to each thread.

If you need your code to run sequentially, then you should not use threads.

Notes apart. Your program has many weird details that would be worth reviewing as well. I'll give you some examples:

  • You do not need your class to inherit Thread . With implementing Runnable is enough and recommended.
  • It is not normal for the instance builder to be assigning a static variable. In this case, it is not a problem, because you are always assigning the same value, but the design is incorrect.
  • The synchronized in your method run does not fulfill any function, since a single thread can run this method for an instance of ficheroSeguro .
  • What probably does require some synchronization is the writeData method, but it would not be enough to add synchronized . It would be necessary to synchronize with some static member. But if you are going to do this, I again question the purpose of using threads.
answered by 28.11.2017 в 19:38