你能告诉我为什么这段代码不起作用?在我看来它应该工作。它在控制台1中写入后停止。我想连续显示秒数,但仅当我发表评论temp = passedTime
然后脚本出错时它才有效
import java.util.ArrayList;
class Timer {
private static long temp = 0;
public static void main(String [] args){
ArrayList<Integer> list = new ArrayList<>();
long startTime = System.currentTimeMillis()/1000;
for (int i=1; i<=1000000; i++) {
list.add(i);
long pasedTime = System.currentTimeMillis()/1000 - startTime;
if (temp != passedTime) {
temp = passedTime;
System.out.println(pasedTime);
}
}
}
}
答案 0 :(得分:0)
我写了一个关于如何在第二个线程上创建计时器的示例,请参见此处:
public class TimerAppExample {
public static class Timer implements Runnable {
private int timer = 5000;
private long startTimer = 0;
private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS");
@Override
public void run() {
startTimer = System.currentTimeMillis();
System.out.println("Started timer at " + simpleDateFormat.format(new Date(startTimer)));
do {
try {
Thread.sleep(1000);
long newTime = System.currentTimeMillis();
System.out.println("Timer event occurred after " + (newTime - startTimer) + " miliseconds at " + simpleDateFormat.format(new Date(newTime)));
timer -= (newTime-startTimer);
startTimer = newTime;
} catch (InterruptedException e) {
e.printStackTrace();
}
} while(timer > 0);
System.out.println("stopped timer at " + simpleDateFormat.format(new Date(startTimer)));
}
}
private void execute() {
Timer timer = new Timer();
Thread thread = new Thread(timer);
System.out.println("Starting timer");
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Timer app ended");
}
public static void main(String[] args) {
TimerAppExample timerAppExample = new TimerAppExample();
timerAppExample.execute();
}
}
输出:
Starting timer
Started timer at 2015-05-16 12:40:31:104
Timer event occurred after 1001 miliseconds at 2015-05-16 12:40:32:105
Timer event occurred after 1000 miliseconds at 2015-05-16 12:40:33:105
Timer event occurred after 1000 miliseconds at 2015-05-16 12:40:34:105
Timer event occurred after 1000 miliseconds at 2015-05-16 12:40:35:105
Timer event occurred after 1000 miliseconds at 2015-05-16 12:40:36:105
stopped timer at 2015-05-16 12:40:36:105
Timer app ended