How can I assign a task to a thread?

0

Good I have a problem with Threads in Java when I execute my program with four Threads the execution time is greater than if I execute it with 1 and I do not understand the reason. Basically what I want is to assign each Threads the number of files to analyze. This is the code that gives me problems.

 public class analiza extends Thread 
{ 
private Stemm_es es;

public analiza() { 
     es = new Stemm_es();
} 

@Override
public void run() { 

    System.out.println(getName()); 

File file1=new File("E:\Escuela\TESIS\Prueba\Prueba\Entrada");
    File [] archivos=file1.listFiles();

    File file=new File("E:\Escuela\TESIS\Prueba\Prueba\Salida\ale.txt");
        try {
            PrintWriter pw = new PrintWriter(file);
    for(int e = 0; e < archivos.length; e++){

        String word ="";
        try {
            Scanner sc=new Scanner(new File("E:\Escuela\TESIS\Prueba\Prueba\Entrada\"+archivos[e].getName()));
             while(sc.hasNextLine())
                {
                  String titulo=sc.nextLine();
                  word+=" "+titulo;
                }
             sc.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Analizar.class.getName()).log(Level.SEVERE, null, ex);
        }


            String [] palabras={"él", "http", "www", "ésta", "éstas", "éste", "éstos", "última", "últimas", "último", "últimos", "a", "añadió", "aún", "aun", "actualmente", "adelante","yo"};
            String [] mama=word.split(" ");
            String [] papa=new String[mama.length];
            int a=mama.length;
            for (int i =0;i<a;i++){   
                for(int l=0;l<palabras.length;l++){
                    if (mama[a-1].equals(palabras[l]))
                    a=a-1;
                    if(mama[i].equals(palabras[l]))  
                    mama[i]="" ;   
                }       
                if (mama[i].length()>=1) {
                    mama[i]=mama[i].replaceAll("[^A-Za-z0-9]", "");
                    mama[i]= mama[i].trim();
                    String raiz= es.stemm(mama[i]);
                    papa[i]=raiz;
                    pw.append(" "+papa[i]);

                }

            }
            pw.println("                                                                                                                 ");


    } 
   pw.close();




} catch (FileNotFoundException ex) {
            Logger.getLogger(Analizar.class.getName()).log(Level.SEVERE, null, ex);
        }

System.out.println("El programa ha finalizado"); 
} 




   public static void main (String[] args) { 


   analiza hiloUno = new analiza(); 
   analiza hiloDos = new analiza(); 
   analiza hiloTres = new analiza();
   analiza hiloCuatro = new analiza();
   hiloUno.start(); 
   hiloDos.start();
   hiloTres.start();
   hiloCuatro.start();
   try {
   hiloUno.join(); 
   hiloDos.join(); 
   hiloTres.join();
   hiloCuatro.join();

   } catch (InterruptedException ie) { 
   }
  System.out.println("El programa ha finalizado"); 
  } 



  } 
    
asked by Alejandro Cuellar 06.03.2018 в 20:34
source

1 answer

0

It's normal to take more, you're not dividing tasks between threads, you're creating four threads with the same task, or at least that's what I think at first glance.

To assign a task to each thread, you should implement four classes that inherit from Thread , but with different implementation of the run method, although this is not always the case.

You can also create threads of the class Thread and pass the different tasks in the constructor, such as anonymous classes that implement the interface Runnable .

Thread t1 = new Thread(new Runnable() {
    public void run() {
        /* Código de la tarea 1 */
    }
});

Thread t2 = new Thread(new Runnable() {
    public void run() {
        /* Código de la tarea 2 */
    }
});

Or, if you use Java 8, you can do it with a lambda expression, which causes the code to be reduced.

Thread t = new Thread(() -> {
        /* El código de la tarea va aquí */
    }
);

In any case you have to keep in mind that the code and the work is not divided alone, nor is the task done faster just because you believe it within a class that inherits Thread .

On some occasions, if you only divide one task in two, it may be that the overhead due to the creation and management of threads can make the program take longer to do a certain task (it is not common, and even less in multiprocessor environments, but it can happen).

    
answered by 08.03.2018 в 01:33