就看了张老师的PPT 没有看视频,没有看代码 自己试着写了一个,可是发现一个问题 先上代码- package com.tra.a;
- /**
- * 灯的开关
- * @author Administrator
- *
- */
- public class lamp {
- /*
- *因为整个系统只有一个灯控制,所以用S2N表示,ture表示s2n为绿灯
- */
- private boolean flag;
-
- public lamp(boolean flag) {
- // TODO Auto-generated constructor stub
- this.flag=flag;
- }
- public void changelamp(){
- if(this.flag) flag=false;
- else flag=true;
- }
- public boolean getlamp(){
- return this.flag;
- }
- }
复制代码- package com.tra.a;
- import java.util.Timer;
- import java.util.TimerTask;
- import com.tra.*;
- public class LampController {
- static lamp l=new lamp(true);
- public boolean checklamp(){
- return l.getlamp();
- }
-
- public void changelamp(){
-
- Timer timer =new Timer();
- timer.schedule(new TimerTask(){
- public void run(){
- l.changelamp();
- if(l.getlamp()==true) System.out.println("s2n绿灯亮");
- else System.out.println("s2n绿灯不亮");
- }
- }, 1000,1000*10);
-
- }
- }
复制代码- package com.tra.a;
- import java.util.LinkedList;
- import java.util.List;
- import java.util.Timer;
- import java.util.TimerTask;
- import java.util.concurrent.ThreadLocalRandom;
- public class Road {
- String[] road={"s2e","e2n","n2w","w2s","s2n","n2s","s2w","n2e","w2e","e2w","w2s","w2n"};
- private List<Integer>[] list = new List[12];
- LampController lc=new LampController();
-
- public void init(){
- for(int i=0;i<12;i++){
- list[i]=new LinkedList<Integer>();
- }
- lc.changelamp();
- }
- public void onroad(){
- init();
- final Timer timer=new Timer();
- timer.schedule(new TimerTask(){
- int k=0;
- public void run(){
- ThreadLocalRandom rand=ThreadLocalRandom.current();
-
- int r=rand.nextInt(1,11);
-
- int c=rand.nextInt(10000,99999);
- list[r].add(c);
- int s=list[r].size();
- System.out.println("方向为 "+road[r]+"路上行来一辆号码为 "+c+"的车 "+"共"+s+"辆在排队");
-
-
- k++;
- //if(k==3) timer.cancel();
- }
-
- }, 0,1000);
-
-
- }
-
- public void outroad(){
- Timer timer1=new Timer();
- timer1.schedule(new TimerTask(){
- public void run(){
- boolean lamp=lc.checklamp();
-
-
- for(int i=0;i<4;i++){
-
- int kk=list[i].size();
- for(int j=0;j<kk-2;j++){
- System.out.println("车牌号为"+list[i].get(j)+"的车从"+road[i]+"的路上行驶过");
- list[i].remove(j);
-
- }
- }
-
- if(lamp){
-
- for(int i=3;i<7;i++){
-
- int kk=list[i].size();
- for(int j=0;j<kk-2;j++){
- System.out.println("车牌号为"+list[i].get(j)+"的车从"+road[i]+"的路上行驶过");
- list[i].remove(j);
-
- }
- }
-
- }
- else{
- for(int i=7;i<12;i++){
-
- int kk=list[i].size();
- for(int j=0;j<kk-2;j++){
- System.out.println("车牌号为"+list[i].get(j)+"的车从"+road[i]+"的路上行驶过");
- list[i].remove(j);
-
- }
- }
-
- }
-
- }
- }, 10000,2000);
-
-
-
- }
-
- }
复制代码- package com.tra.a;
- import com.tra.*;
- public class Main {
- public static void main(String[] args){
- Road r=new Road();
- r.onroad();
- r.outroad();
- }
- }
复制代码 |
|