交通灯管理系统Road类

来源:互联网 发布:易语言刷枪源码 编辑:程序博客网 时间:2024/06/05 12:42
package com.mth.bean;/* * 交通灯系统  Road类 *  * */import java.util.ArrayList;import java.util.List;import java.util.Random;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;public class Road {// 存车private List<String> carList = new ArrayList<String>();// 路的名字private String name;public Road(String name) {this.name = name;// 创建一个线程池 来造车ExecutorService pool = Executors.newFixedThreadPool(1);pool.execute(new Runnable() {public void run() {for (int i = 0; i < 1000; i++) {try {// 每隔1-10秒钟之内 增加一辆车Thread.sleep((new Random().nextInt(10) + 1) * 1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}// 访问外部类的成员变量 格式: 外部类的名字+this+变量名字carList.add(Road.this.name + "..." + i);}}});// 定时器 移走车ScheduledExecutorService timer = Executors.newScheduledThreadPool(1);// scheduleAtFixedRate(Runnable command, long initialDelay, long period,// TimeUnit unit)/* * 第一个参数就是 要执行的任务 第二个参数就是 过多少秒以后去做这个任务 第三个参数就是 干完以后在过多少秒接着做 第四个参数就是 时间单位 */timer.scheduleAtFixedRate(new Runnable() {public void run() {if (carList.size() > 0) {// 有车才移走车boolean b = Lamp.valueOf(Road.this.name).isLighted();if (b) {// 移走第一辆车System.out.println(carList.remove(0) + "正在移动");}}}}, 1, 1, TimeUnit.SECONDS);}}

0 0
原创粉丝点击