永发信息网

java控制红绿灯及模拟车辆运动

答案:3  悬赏:50  手机版
解决时间 2021-03-22 12:36
  • 提问者网友:山高云阔
  • 2021-03-21 13:37
java控制红绿灯及模拟车辆运动
最佳答案
  • 五星知识达人网友:掌灯师
  • 2021-03-21 15:00
交通灯一个类,汽车一个类。用多线程实现同步,代码如下:
public class Temp
{
public static final Boolean RED=false;
public static final Boolean GREEN=true;
Boolean lightControl=GREEN;
Light light=new Light();
Car car=new Car();

public static void main(String[] args){
Temp temp=new Temp();
temp.start();
}

public void start()
{
light.print();
Thread lightThread=new Thread(new Runnable(){
public void run(){
light.run();
}
});
Thread carThread=new Thread(new Runnable(){
public void run(){
car.run();
}
});
lightThread.start();
carThread.start();
}

class Light
{
public void count(){
short count=5;
while (count>-1)
{
try
{
Thread.sleep(1000);
System.out.println("还有"+count+"秒");
count--;
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
change();
}

public void change(){
lightControl=!lightControl;
print();
}

public void print(){
if(lightControl){
System.out.println("现在是绿灯!");
}else{
System.out.println("现在是红灯!");
}
}

public synchronized void run(){
while(true){
count();
if (lightControl)
{
car.go();
}
}
}
}

class Car
{
public synchronized void go(){
this.notify();
}

public synchronized void stop(){
System.out.println(" 汽车停止");
try
{
this.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}

}

public void run(){
while(true){
if(!lightControl){this.stop();}
System.out.println(" 汽车运行");
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}
全部回答
  • 1楼网友:荒野風
  • 2021-03-21 16:40
信号灯一个类汽车一个类,规定信号灯和汽车的行为。主方法用两个线程控制实体对象的行为。试试吧,应该不难。
  • 2楼网友:琴狂剑也妄
  • 2021-03-21 15:56
写两个程序分别模拟红绿灯和汽车:
1)红绿灯程序以报文形式通知汽车程序;
2)汽车程序需要用多线程来实现。
3)红绿灯程序用个循环,每隔n分钟红绿灯转换,同时通知汽车程序;
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯