Sale.java:
import java.util.ArrayList;
import java.util.Random;
public class Sale implements Runnable
{
public int index;
private ArrayList<Integer> al=new ArrayList<Integer>();
Random rd=new Random();
public Sale(){
for(int i=1;i<1001;i++){
al.add(new Integer(i));
}
}
//加入一个同步方法
public synchronized void fun(){
if(al.size()>0){
try{
Thread.sleep(30);
}catch(Exception e){
}
index=rd.nextInt(al.size());
System.out.println(Thread.currentThread().getName()+"卖了一张编码为"+al.get(index)+"的火车票!");
al.remove(index);
}
}
public void run(){
while(al.size()>0){
this.fun();
}
}
}