假设车库有3个车位,写一个程序模拟多个用户开车离开,停车入库的效果。
import java.util.Random;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Executor pool=Executors.newCachedThreadPool();
Pos pos=new Pos();
for(int i=1;i<=10;++i)
pool.execute(new Car(i, pos));
}
}
class Pos{
boolean[] wei=new boolean[3];
public Pos(){
for(int i=0;i<wei.length;++i)
wei[i]=true;
}
public int tiche(Car car){
while(true)
synchronized (Pos.class) {
for(int i=0;i<wei.length;++i)
if(wei[i]){
wei[i]=false;
System.out.println(car.name+"停在"+i+"号库");
return i;
}
}
}
public void out(Car car){
while(true)
synchronized (Pos.class) {
wei[car.num]=true;
System.out.println(car.name+"离开"+car.num+"号库");
return;
}
}
}
class Car implements Runnable{
int name;
int num;
Pos pos;
public Car(int name, Pos pos) {
super();
this.name = name;
this.pos = pos;
}
@Override
public void run() {
// TODO Auto-generated method stub
this.num = pos.tiche(this);
try {
Thread.sleep(Math.abs(new Random().nextInt())%10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pos.out(this);
}
}