黑马程序员技术交流社区
标题:
交通灯系统左转和直行的时间不一样,怎么写?
[打印本页]
作者:
姜志钦
时间:
2012-4-20 09:44
标题:
交通灯系统左转和直行的时间不一样,怎么写?
我试着写左转和直行的时间不一样,试几种方法都不行,可能是我对多线程掌握不好,以下是写两个计时器,也不行。怎么写才可以?
boolean flag=false;
Lock lock=new ReentrantLock();
Condition condition=lock.newCondition();
Condition conTimer=lock.newCondition();
Condition conTimer1=lock.newCondition();
public LampController(){
currentLamp=Lamp.StoN;
currentLamp.light();
final ScheduledExecutorService timer=Executors.newScheduledThreadPool(1);
final ScheduledExecutorService timer1=Executors.newScheduledThreadPool(1);
timer.scheduleAtFixedRate(new Runnable() {
long start=System.currentTimeMillis();
@Override
public void run() {
lock.lock();
System.out.println(currentLamp.name());
if(currentLamp==Lamp.StoW||currentLamp==Lamp.EtoS){ flag=true;}
try {
while (flag){
conTimer.await();
conTimer1.signal(); }
currentLamp=currentLamp.blackout();
long end=System.currentTimeMillis();
System.out.println(end-start);
start=end;
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} finally {
lock.unlock();
}
}
},10,10,TimeUnit.SECONDS);
timer1.scheduleAtFixedRate(new Runnable() {
long start=System.currentTimeMillis();
@Override
public void run() {
lock.lock();
// System.out.println(currentLamp.name());
if(currentLamp==Lamp.StoN||currentLamp==Lamp.EtoW){ flag=false; }
try {
while (!flag){
conTimer1.await();
conTimer.signal(); }
/*wait();
timer.notify();*/
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} finally {
lock.unlock();
}
long end=System.currentTimeMillis();
System.out.println(end-start);
start=end;
currentLamp=currentLamp.blackout();
}
},5,5,TimeUnit.SECONDS);
}}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2