刚刚写了一个模拟红绿灯的JAVA程序,有点小问题,请各位指教!
虽然调试通过,可是总觉得有点问题。
代码:
package test;
import java.util.Timer;
import java.util.TimerTask;
public class LightTest
{
private final Timer timer = new Timer();
private final int second;
private final int color;
public LightTest( int second, int color )
{
this.second = second;
this.color = color;
}
public void DisplayLight( int color )
{
switch( color )
{
case 1:
{
System.out.println( "红灯亮 " );
break;
}
case 2:
{
System.out.println( "黄灯亮 " );
break;
}
case 3:
{
System.out.println( "绿灯亮 " );
break;
}
default:
{
System.out.println( "输入参数错误! " );
break;
}
}
}
public void start()
{
DisplayLight( color );
timer.schedule( new TimerTask()
{
public void run()
{
timer.cancel();
}
}, second*1000 );
}
public static void main(String[] args)
{
while ( true )
{
LightTest green = new LightTest( 14, 3 );
green.start();
LightTest yellow = new LightTest( 6, 2 );
yellow.start();
LightTest red = new LightTest( 20, 1 );
red.start();
}
}
}
运行时发现在控制台显示的时间并不是我定义的时间间隔。而是时快时慢。困惑~~
请各位高手指点!谢谢!
[解决办法]
在timer.schedule( new TimerTask()
{
public void run()
{
timer.cancel();
}
}, second*1000 );
}
中用的是timer.shedule(new TimerTask(),senconds*1000);改为timer.shedule(new TimerTask(),0,seconds*1000);就对了.在括号里的后俩参数分别代表的什么时候开始和延迟多久.
[解决办法]
修正一下
import java.util.Timer;
import java.util.TimerTask;
public class LightTest
{
static long start_time;
private final Timer timer = new Timer();
private final int second;
private final int color;
public LightTest(int second, int color) {
this.second = second;
this.color = color;
}
public void DisplayLight(int color) {
switch (color) {
case 1: {
System.out.println( "红灯亮 ");
break;
}
case 2: {
System.out.println( "黄灯亮 ");
break;
}
case 3: {
System.out.println( "绿灯亮 ");
break;
}
default: {
System.out.println( "输入参数错误! ");
break;
}
}
}
public void start() {
//DisplayLight(color);
timer.schedule(new TimerTask(){
public void run(){
DisplayLight(color);
System.out.println((System.currentTimeMillis() - start_time) + "毫秒\r\n ");
}
}, 0, second * 1000);
}
public static void main(String[] args) {
start_time = System.currentTimeMillis();
//while (true) {
LightTest green = new LightTest(14, 3);
green.start();
LightTest yellow = new LightTest(6, 2);
yellow.start();
LightTest red = new LightTest(20, 1);
red.start();
//}*/
/*Timer tr = new Timer();
tr.schedule(new TimerTask() {
public void run() {
System.out.println(100);
}
}, 0, 1000);*/
}
}