Home > Software design >  Random number and threads
Random number and threads

Time:01-02

I've got problem with threads. I'm running "run" method using three object, each in a different thread.

Is it possible to get the same number from three threads? I suppoused that the answer is no, but is it possible after some change ?

Main:

public static void main(String[] args) {
    
   Test w1,w2,w3;
    
    w1 = new Test(1);
    w2 = new Test(2);
    w3 = new Test(3);
    
    w1.start();
    w2.start();
    w3.start();

}

class:

public class Test extends Thread implements Runnable{
int number;

public Test(int number) {
    this.number = number;
}

@Override
public void run() {
    Random rnd = new Random();
    
    //int pom = ThreadLocalRandom.current().nextInt(101);
    int pom = rnd.nextInt(101);
    System.out.println("Random number: " pom ", number of thread: " number);
}

}

CodePudding user response:

Sure. Each thread makes an instance of Random and then pulls the same number of bytes out of it (namely: 1 int between 0 and 100 inclusive). Thus, if they are all the same random sequence, you'd get the same results.

Initialize them all with a set seed value and you get what you want. If you prefer, you can do this so that every invocation of this process, you get a different seed value (so, random seed), but that all randoms run the same way:

Main:

public static void main(String[] args) {
   Test w1,w2,w3;
   
   long seed = new Random().nextLong();
    w1 = new Test(1, seed);
    w2 = new Test(2, seed);
    w3 = new Test(3, seed);
    
    w1.start();
    w2.start();
    w3.start();
}

class:

public class Test extends Thread {
  private final int number;
  private final Random rnd;

  public Test(int number, long seed) {
    this.number = number;
    this.rnd = new Random(seed);
  }
  
  @Override
  public void run() {
    int pom = rnd.nextInt(101);
    System.out.println("Random number: " pom ", number of thread: " number);
  }
}

I also cleaned up some style issues (private final on the fields, it makes more sense to me to have the instance of Random be a field instead of having a field to store the seed separately.

  • Related