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

本文介绍了一个使用Java实现的电梯运行模拟系统。该系统通过多线程技术模拟了电梯上下行及乘客进出的过程。乘客随机生成并设定目标楼层,电梯则根据当前方向自动调整停靠楼层。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 + "]";
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值