Problem when doing an exercise with threads in Java

1

Good, today started with threads and I am a little lost, I made the following code to make a program with two threads of name "HiloUno" and "HiloDos" so that each of them visualize the first 10 natural numbers . But I think I've got it wrong.

Code:

public class Ejercicio1Hilos extends Thread
{   
    public void run() 
    {
        System.out.println("Hilo1");
        System.out.println("Hilo2");
    }

    public static void main(String[] args)
    {
        Ejercicio1Hilos myThread1 = new Ejercicio1Hilos();
        Ejercicio1Hilos myThread2 = new Ejercicio1Hilos();

        for(int i=1;i<=10;i++)
        {
            myThread1.start();
            myThread2.start();
        }
    }
}
    
asked by Mario Guiber 26.10.2017 в 21:50
source

1 answer

4

Complementing what you wrote in the comments, I think you're on the right track, but the logic is in the wrong places.

You are creating and starting the threads very well, but what you are doing is starting both threads 10 times and each thread is printing

  

Hilo1
  Hilo2

What this does is that an exception occurs (in the worst case for a IllegalThreadStateException ) and does not allow you to continue. If it were not for the exception, I would be printing the above 20 times.

If I understand correctly what you want, what you have to do is pass the cycle you have ( for ) inside the run method:

public void run() {
    for (int i = 1; i <= 10; i++) {
    ...
    }
}

and within for you can print the counter itself:

System.out.println(i);

Now, taking into account the comments made to you, you can have a constructor for your class that receives the name of your thread:

private String nombre;

public Ejercicio1Hilos(final String nombre) {
    this.nombre = nombre;
}

and print the name plus the counter:

System.out.println(nombre + " " + i);

Finally, when you create the instance of your threads, you do it by passing the name you want:

Ejercicio1Hilos myThread1 = new Ejercicio1Hilos("Hilo 1");

and the final result will be something like this:

  

Thread 1 1
  Thread 2 1
  Thread 1 2
  Thread 2 2
  Thread 1 3
  Thread 2 3
  Thread 1 4
  Thread 1 5
  Thread 2 4
  Thread 1 6
  Thread 2 5
  Thread 1 7
  Thread 2 6
  Thread 1 8
  Thread 1 9
  Thread 2 7
  Thread 1 10
  Thread 2 8
  Thread 2 9
  Thread 2 10

NOTE: It may not be the same as what I just put you, because that is the beauty of the threads, they run at the same time and you do not know in what order they are running.

Another thing, I put all the puzzle, just need to put it in place and have fun trying and trying.

    
answered by 27.10.2017 / 11:13
source