Foro de elhacker.net

Programación => Java => Mensaje iniciado por: Norochii en 18 Septiembre 2013, 08:51 am



Título: Problema con Threads en Java
Publicado por: Norochii en 18 Septiembre 2013, 08:51 am
Que tal buenos dias, quisiera ver si me podrian ayudar con mi programa, lo que pasa es que lo estoy haciendo con Threads pero cuando entra al metodo run no ejecuta el metodo de ordenamiento. El programa tiene que hacer el ordenamiento Burbuja de 25000 numero generados aleatoriamente por medio de Threads, hice que funcionara sin Threads pero cuando lo hago por medio de Hilos no se ejecuta la funcion de ordenamientos y la verdad no se por que (cabe mencionar que sin hilos funciona a la perfeccion), pero con hilos me sale el siguiente error. Espero me puedan ayudar.

Saludos.

Exception in thread "Thread-0" java.lang.NullPointerException
   at ordenamientos.Bubble.bubble_sort(Bubble.java:52)
   at ordenamientos.Bubble.run(Bubble.java:38)
   at java.lang.Thread.run(Thread.java:724)


Este es el codigo de mi programa.


package ordenamientos;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class Bubble implements Runnable
{
   Thread t;
   public int [] matrix;
   
   final void setMatriz(int matriz[])
   {
      matrix = matriz;
   }
   
   int[] getMatriz()
   {
      return matrix;
   }
   
   public Bubble()
   {
   }
   
   public Bubble(int matriz[])
   {
      matrix = matriz;
      
   }
   
   public void run()
   {
      System.out.println("Aqui deberia estar corriendo el ordenamiento burbuja :/");
      bubble_sort(getMatriz());
      
   }
   
   public void bubble_sort(int matriz[])
   {
      long comienza = System.currentTimeMillis();
      int buffer;
      int i,j;
      
      for(i = 0; i < 25000; i++)
      {
         for(j = 0; j < i; j++)
         {
            if(matriz < matriz [j])
            {
               buffer = matriz[j];
               matriz[j] = matriz;
               matriz = buffer;
            }
         }
         
      }
      
      for(int x = 0; x < matriz.length; x++)
      {
         System.out.println("Numeros: " + matriz
  • );
      }
      long termina = System.currentTimeMillis();
      long tiempoTranscurrido = termina - comienza;
      System.out.println("\n\nTiempo transcurrido con el metodo de ordenamiento Burbuja: " + tiempoTranscurrido + " milisegundos");
      
          try
          {
             File TextFile = new File("/home/norochii/workspace/Ordenamientos/Tiempos.odt");
             FileWriter TextOut = new FileWriter(TextFile, true);
             TextOut.write ("Ordenamiento Burbuja: "+tiempoTranscurrido + " Milisegundos"+"\r\n");
             TextOut.close();
          }
          catch(IOException e)
          {   
               System.out.println("Error!!");       
          }
   }

}




package ordenamientos;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.Random;
import ordenamientos.Bubble;

public class Principal
{   
   public static void main(String[] args)
   {
      int [] arreglo;
      arreglo = new int [25000];
      
      Shell shell = new Shell();
      Bubble burbuja = new Bubble();
      Insercion insercion = new Insercion();
      
      @SuppressWarnings("resource")
      Scanner entrada = new Scanner(System.in);
      Random numero_aleatorio = new Random();
      
      if(burbuja.matrix == shell.matrix && burbuja.matrix == insercion.matrix )
      {
         if(shell.matrix == burbuja.matrix && shell.matrix == insercion.matrix)
         {
            if(insercion.matrix == burbuja.matrix && insercion.matrix == shell.matrix)
            {
               System.out.println("Datos: " );
               for(int x = 0; x<arreglo.length; x++)
               {
                  int valor;
                  valor = numero_aleatorio.nextInt(250000);
                  arreglo
  • = valor;
                  System.out.println(valor);
                  
                  try
                     {
                         File TextFile = new File("/home/norochii/workspace/Ordenamientos/Numeros sin Ordenar.odt");
                         FileWriter TextOut = new FileWriter(TextFile, true);
                         TextOut.write (valor +"\r\n");
                         TextOut.close();
                     }
                     catch(IOException e)
                     {
                           System.out.println("Error!!");   
                     }
                  
                  
               }
               
               System.out.println("\n\nGeneracion de numeros aleatorios lista.");
               System.out.print("Presiona cualquier tecla para continuar: ");
               entrada.nextLine();
               System.out.println("\n\n\n\n");
               
               
               System.out.println("Ordenamiento Shell: ");
               System.out.println("\n\n\n\n\n\n");
               shell.shell_sort(arreglo);
               try {
                  Thread.sleep(4000);
               } catch (InterruptedException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
               }
               
               
               System.out.println("\n\n\n\n");
               System.out.println("Ordenamiento Burbuja: ");
               System.out.println("\n\n\n\n\n\n");
               //burbuja.bubble_sort(arreglo);
               
               Thread hilo = new Thread(burbuja);
               hilo.start();
               
               //new Thread(burbuja).start();
               try {
                  Thread.sleep(4000);
               } catch (InterruptedException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
               }
               System.out.println("Ordenamiento Insercion: ");
               insercion.insercion_sort(arreglo);
      
            
               System.out.println("\n\n\n\n\n\n");
               
               
               
            }
         }
      }
   }

}




Título: Re: Problema con Threads en Java
Publicado por: Fakedo0r en 18 Septiembre 2013, 13:33 pm
Estoy en el despacho y no tengo ningún IDE de Java instalado pero mirando así...

Estas lineas:

Código
  1. if(matriz < matriz [j])
  2. {
  3.     buffer = matriz[j];
  4.     matriz[j] = matriz;
  5.     matriz = buffer;
  6. }


matriz[j] = matriz; <== esta mal.

Veo otros fallos también. Revisa-te el código amigo...


Título: Re: Problema con Threads en Java
Publicado por: Mitsu en 18 Septiembre 2013, 20:36 pm
Hola. No soy un experto en Java y quizás me equivoque en lo que voy a decirte, pero

Código
  1. if(matriz < matriz [j])
  2. {
  3.     buffer = matriz[j];
  4.     matriz[j] = matriz;
  5.     matriz = buffer;
  6. }

¿Qué quiere decir?.. :

Código
  1. if (matriz < matriz[j])

Esta línea no compara absolutamente nada. 'matriz' es un arreglo y no puedes compararlo con un valor sin especificar qué es lo que deseas comparar, como longitud (.length) o algún valor dentro del arreglo (matriz). Estás confundiendo matriz con arreglo. Una matriz es un arreglo bidimensional.

En la línea:

Código
  1. matriz[j] = matriz

¿Qué se supone que vas a guardar en matriz[j]?

No puedes guardar todo un arreglo en un subíndice de un arreglo.

Si te fijas, el error que tira es NullPointerException. Este error lo tira cuando se intenta manipular un dato que no existe.


Revisa esas líneas que seguro encontrarás el error.



Saludos.


Título: Re: Problema con Threads en Java
Publicado por: Norochii en 23 Septiembre 2013, 10:46 am
muchas gracias M1τѕυ era parte de mi problema eso que me mencionas agradezco que me hayas ayudado y gracias a corregir eso y otras cosillas pude hacerlo funcionar. Saludos :D