交通灯管理系统Road类

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 block
						e.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);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值