Get random boolean in Java

2019-03-11 13:33发布

Okay, I implemented this SO question to my code: Return True or False Randomly

But, I have strange behavior: I need to run ten instances simultaneously, where every instance returns true or false just once per run. And surprisingly, no matter what I do, every time i get just false

Is there something to improve the method so I can have at least roughly 50% chance to get true?


To make it more understandable: I have my application builded to JAR file which is then run via batch command

 java -jar my-program.jar
 pause

Content of the program - to make it as simple as possible:

public class myProgram{

    public static boolean getRandomBoolean() {
        return Math.random() < 0.5;
        // I tried another approaches here, still the same result
    }

    public static void main(String[] args) {
        System.out.println(getRandomBoolean());  
    }
}

If I open 10 command lines and run it, I get false as result every time...

9条回答
霸刀☆藐视天下
2楼-- · 2019-03-11 14:14

Why not use the Random class, which has a method nextBoolean:

import java.util.Random;

/** Generate 10 random booleans. */
public final class MyProgram {

  public static final void main(String... args){

    Random randomGenerator = new Random();
    for (int idx = 1; idx <= 10; ++idx){
      boolean randomBool = randomGenerator.nextBoolean();
      System.out.println("Generated : " + randomBool);
    }
  }
}
查看更多
淡お忘
3楼-- · 2019-03-11 14:16

Java 8: Use random generator isolated to the current thread: ThreadLocalRandom nextBoolean()

Like the global Random generator used by the Math class, a ThreadLocalRandom is initialized with an internally generated seed that may not otherwise be modified. When applicable, use of ThreadLocalRandom rather than shared Random objects in concurrent programs will typically encounter much less overhead and contention.

java.util.concurrent.ThreadLocalRandom.current().nextBoolean();
查看更多
欢心
4楼-- · 2019-03-11 14:17

You could also try nextBoolean()-Method

Here is an example: http://www.tutorialspoint.com/java/util/random_nextboolean.htm

查看更多
登录 后发表回答