初级JAVA单线程模拟电梯运行

package zxr;

import java.util.*;
public class Life implements Runnable{
Random rand = new Random();
//当前电梯人数
// persons = rand.nextInt(maxPersons);
private int maxPersons = 15;
List<Person>  personList = new ArrayList<Person>();
boolean upFlag = true;
//总层数
int maxPlies = 15;
//当前层数
int currentPlies = 1;
//目标层数
int plies ;
public void biuldPersons(){
int count = rand.nextInt(10);
for(int i = 0; i <count ; i++){
//判断当前电梯里的人数是否达到了上限
if(personList.size() == maxPersons){
//随机在当前楼层生成几个要进入电梯的人,也可以是0
break;
}
Person person = new Person();
personList.add(person);
person.startFloor = currentPlies;
person.targetFloor = rand.nextInt(14)+1;
}
}
public void run(){
while(true){
try {
Thread.sleep(2000);
if(upFlag)
currentPlies++;
else
currentPlies--;
if(1 == currentPlies)
upFlag=true;
if(15 == currentPlies)
upFlag = false;
//重算当前楼层的人数
List<Person> list = new ArrayList<Person>();
list.addAll(personList);
int oldCount = personList.size();
for(Person p : list){
//删除电梯列表里的这个人,注意删除这个动作需要从列表的后面向前面删,否则可能有问题,在容器这一章有删除练习出过问题
if(p.targetFloor == currentPlies){
personList.remove(p);
}
}
int tmpCount = personList.size();
biuldPersons();
int lastCount = personList.size();
System.out.println("当前第几层:"+currentPlies);
System.out.println("电梯里有多少人:"+personList.size());
System.out.println("所有人:"+personList);
System.out.println("上了几个人:"+(lastCount-tmpCount)+";下了多少人:"+(oldCount-tmpCount));



} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}
public static void main(String[] args){
Thread th = new Thread(new Life());
th.start();
}
}
class Person{
//出发楼层
int startFloor;
//目标楼层
int targetFloor ;
@Override
public String toString() {
return "Person [startFloor=" + startFloor + ", targetFloor="
+ targetFloor + "]";
}

}

猜你喜欢

转载自zengxianrong11.iteye.com/blog/2146772