Random speed on Java threads

1

I have done a small program simulating a race with three threads. My idea is to put these speeds with randoms number so that the result varies, but I do not know how to do it.

Code:

public class Carrera extends Thread
{
    String nombre;
    int velocidad;

    public Carrera(String nombre,int velocidad) 
    {
        this.nombre = nombre;
        this.velocidad = velocidad;
    }

    public void run()
    {
        for(int i=1;i<=12;i++)
        {
            System.out.print(nombre+" ");
            try {
                sleep(1000/velocidad);
            } catch (InterruptedException e) {e.printStackTrace();}
        }
        System.out.println("Terminó: "+nombre);
    }

    public static void main(String[] args)
    {
        Carrera friki1 = new Carrera("f1", 4);
        Carrera friki2 = new Carrera("f2", 3);
        Carrera friki3 = new Carrera("f3", 1);

        friki1.start();
        friki2.start();
        friki3.start();
    }
}
    
asked by Mario Guiber 28.10.2017 в 18:12
source

1 answer

1

You can use the class Random :

public static void main(String[] args) {
    Random random = new Random();
    Carrera friki1 = new Carrera("f1", random.nextInt(10));
    Carrera friki2 = new Carrera("f2", random.nextInt(10));
    Carrera friki3 = new Carrera("f3", random.nextInt(10));

    friki1.start();
    friki2.start();
    friki3.start();
}
    
answered by 28.10.2017 / 20:42
source