Pav*_*cek 62 java random boolean
好的,我在我的代码中实现了这个SO问题:随机返回True或False
但是,我有一些奇怪的行为:我需要同时运行十个实例,其中每个实例每次运行只返回一次true或false.令人惊讶的是,无论我做什么,每次我得到的都是false
有没有什么可以改进方法,所以我至少有大约50%的机会获得true?
为了使它更容易理解:我将我的应用程序构建到JAR文件,然后通过批处理命令运行
java -jar my-program.jar
pause
Run Code Online (Sandbox Code Playgroud)
程序的内容 - 使其尽可能简单:
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());
}
}
Run Code Online (Sandbox Code Playgroud)
如果我打开10个命令行并运行它,我false每次都得到结果......
aio*_*obe 94
我推荐使用 Random.nextBoolean()
话虽这么说,Math.random() < 0.5因为你也使用了作品.这是我机器上的行为:
$ cat myProgram.java
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());
}
}
$ javac myProgram.java
$ java myProgram ; java myProgram; java myProgram; java myProgram
true
false
false
true
Run Code Online (Sandbox Code Playgroud)
毋庸置疑,每次都无法获得不同的价值.但是,在你的情况下,我怀疑
A)你没有使用你认为的代码,(比如编辑错误的文件)
B)你在测试时没有编译你的不同尝试,或者
C)你正在使用一些非标准的破坏实现.
小智 24
你有没有试过看太阳的(oracle)文档?
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Random.html#nextBoolean()
无论如何这里的示例代码:
java.util.Random
Random random = new Random();
random.nextBoolean();
Run Code Online (Sandbox Code Playgroud)
Java 8:使用隔离到当前线程的随机生成器:ThreadLocalRandom nextBoolean()
像Math类使用的全局Random生成器一样,ThreadLocalRandom会使用内部生成的种子进行初始化,否则无法进行修改。如果适用,在并发程序中使用ThreadLocalRandom而不是共享Random对象通常会遇到更少的开销和争用。
java.util.concurrent.ThreadLocalRandom.current().nextBoolean();
Run Code Online (Sandbox Code Playgroud)