本帖最后由 郑传庆 于 2012-6-15 13:06 编辑
下面一个简单的定时器,我想看一下每运行一次要的时间是否是1秒,可我在nunnable2 里面打印为什么获取不到当前的时间呢?大家帮忙看下
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Road {
private static List<String> lst = new ArrayList<String>();;
private static String name =null;
@SuppressWarnings("static-access")
public Road(String name){
this.name = name;
ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1);
scheduled.scheduleAtFixedRate(
nunnable2,
1,//过多少秒运行
1,//过多少秒接着继续
TimeUnit.SECONDS);//秒
}
static Runnable nunnable1 = new Runnable() {
public void run(){
for(int i=1;i<5;i++){
try {
Thread.sleep((new Random().nextInt(10) + 1) * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
lst.add(name + "_" + i);
}
return;
}
};
Runnable nunnable2 = new Runnable() {
@Override
public void run() {
if(lst.size()>0){
boolean lighted = true;
if(lighted){//为什么我这里获取不到时间?
long st = System.currentTimeMillis();
String num = lst.remove(0);
System.out.println(num + " ,您好");
long et = System.currentTimeMillis();
long time = (et-st);
System.out.println(num+"时间是:"+ time +"\n");
}
}
}
};
public static void main(String args[]){
Road road = new Road("集合");
new Thread(nunnable1).start();
}
}
大家如果还有什么好的建议,可以提出来交流一下
|