以前写的给你参考参考
class RunDemo implements Runnable{
private static double[] num = null;
private int count = 6;
public RunDemo(){
this.num = new double[count];
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<3;i++){
this.set();
//System.out.println("num["+i+"]:"+this.num[i]);
}
}
public synchronized void set(){
if(this.count > 0){
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
count--;
this.num[this.num.length -(this.count+1)] = this.getNum();
System.out.println(Thread.currentThread().getName()+"-->num["+(this.num.length -(this.count+1))+"]:"
+this.num[this.num.length -(this.count+1)]);
}
}
public double getNum(){
return Math.round(Math.random()*30+1+50)/100.0;
}
}
public class Test7 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
RunDemo r = new RunDemo();
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
t1.start();
t2.start();
}
} |