日期:2014-05-20 浏览次数:20646 次
import java.util.*;
public class RandomGenMultiThread implements Runnable{
private int randomNum;
private long seed;
private int num;
public RandomGenMultiThread(int num){
Date date = new Date();
this.seed = date.getTime();
this.num = num;
}
@Override
public void run(){
Random random = new Random(this.seed);
for(int i=0;i < 25000;i++){
this.randomNum = random.nextInt();
System.out.println("random number "+this.randomNum+" from thread " + this.num);
}
}
public static void main(String[] args){
RandomGenMultiThread r1 = new RandomGenMultiThread(1);
RandomGenMultiThread r2 = new RandomGenMultiThread(2);
RandomGenMultiThread r3 = new RandomGenMultiThread(3);
RandomGenMultiThread r4 = new RandomGenMultiThread(4);
new Thread(r1).start();
new Thread(r2).start();
new Thread(r3).start();
new Thread(r4).start();
}
}
public static void main(String[] args) {
for (int i = 0; i < 4; i++) {
Runnable task = new Runnable() {
public void run() {
for (int j = 0; j < 25000; j++) {
System.out.println(new Random().nextInt(100000));
}
}
};
new Thread(task).start();
}
}
for (int i = 0; i <= 4; i++) {
new Thread() {
@Override
public void run() {
for (int j = 0; j < 25000; j++) {
System.out.println(new Random().nextInt(100000));
}
}
}.start();
}
public void run(){
synchronized(System.out){
Random random = new Random(this.seed);
for(int i=0;i < 25000;i++){
this.randomNum = random.nextInt();
System.out.println("random number "+this.randomNum+" from thread " + this.num);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}