主程序启动若干线程, 每个线程打印一个随机数, 为什么每次运行, 打印出来的随机数都是一样的呢?
程序如下, 请高手帮忙看看
============================
public class Test implements Runnable {
public Test() { } public void run(){
System.err.println(getRandomNumber(0, 1000));
} public int getRandomNumber(int min, int max) {
Random random = new Random();
//最大循环随机的次数
int maxTimes = 10;
int res;
int count = 0;
for (res = random.nextInt(max); res >= min; count++) {
if (count >= maxTimes) {
res = min + res;
break;
}
}
return res;
}
public static void main(String[] args) throws InterruptedException {
Test t = new Test();
for (int i = 0; i < 6; i ++){
new Thread(t).start();
}
}
}
程序如下, 请高手帮忙看看
============================
public class Test implements Runnable {
public Test() { } public void run(){
System.err.println(getRandomNumber(0, 1000));
} public int getRandomNumber(int min, int max) {
Random random = new Random();
//最大循环随机的次数
int maxTimes = 10;
int res;
int count = 0;
for (res = random.nextInt(max); res >= min; count++) {
if (count >= maxTimes) {
res = min + res;
break;
}
}
return res;
}
public static void main(String[] args) throws InterruptedException {
Test t = new Test();
for (int i = 0; i < 6; i ++){
new Thread(t).start();
}
}
}
Random不是你想象的那样,看
http://community.csdn.net/Expert/topic/5207/5207454.xml?temp=.243786你把random设置成类变量,new一次,每次取的时候同步一下就可以了