首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

急java多线程,该怎么解决

2013-04-02 
急!!!java多线程生成10000个随机数,用4个线程均分为4块怎么分啊?[解决办法]代码如下:import java.util.*p

急!!!java多线程
生成10000个随机数,用4个线程均分为4块怎么分啊?
[解决办法]
代码如下:


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();
}

[解决办法]
引用:
代码如下:
Java code?12345678910111213141516171819202122232425262728293031323334import java.util.*; public class RandomGenMultiThread implements Runnable{    private int randomNum;    private……

感觉run()方法这样写好些。。。
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();
}
}

}           

[解决办法]

public static LinkedList<Integer> arrayList = new LinkedList<Integer>() ;
public static int MaxSize = 100000 ; 
public static synchronized void add(int i){
 if( arrayList.size() < MaxSize){
    arrayList.add(i) ;
}
}
public static synchronized boolean isOk(){
if(arrayList.size()>= MaxSize)
return false;
return true;
}
public static void main(String[] args) {
for (int i = 0; i < 4; i++) {       
new Thread() {           
@Override          
public void run() {    
while(isOk()){ 
add(new Random().nextInt(MaxSize)) ;
}
}     
}.start();   

}
}

热点排行