交通燈管理系統基礎知識篇

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);


	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章