class
{
public static void main(String[] args)
{
/*
*基础知识 :
关于java5的开启新线程的方法
如张老师所说:记得Executors 就好了
ExecutorService pool = Executors.newSingleThreadExecutor();
pool.execute(new Runnable({});
自己的理解: Executors 是一个工具类 调用 newSingleThreadExecutor
是返回一个新的单线程但是这个线程是没有被具体定义。
ExecutorService 是一个接口 查看方法 有一个execute 方法 要求传入Runnable的接口对象
故复写run方法定义线程 并执行
下面的定时器也可以这么理解
*/
/*基础知识 :
设置定时器的相关代码:
ScheduleExecutorService timer= Executors.newScheduledThreadPool(1);
timer.ScheduleAtFixedrate(Runnable target,delay,period,type_of_time)
delay: 第一次执行前的延迟;
period : 每次执行间隔
tupe_of_time : 前两种时间的类型 具体的为TimeUnit.操作。
*/
//每隔一秒检查对应的灯是否为绿,是则放行一辆车
ScheduledExecutorService timer = Executors.newScheduledThreadPool(1);
timer.scheduleAtFixedRate(
new Runnable(){
public void run(){
if(vechicles.size()>0){
lighted = true;//先暂时设置为true,应该是判断当前灯的状态。
if(lighted){
System.out.println(vechicles.remove(0) + " is traversing !");
}
}
}
},
1,
1,
TimeUnit.SECONDS);
}
}
交通灯管理系统基础知识篇
最新推荐文章于 2024-06-16 12:06:38 发布