Can you tell me please why this code doesn't work? In my opinion it should work. It stops after is written in the console 1. I want to show consecutive seconds, but It works only if I comment temp = passedTime
and then the script goes wrong
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);
}
}
}
}
I wrote you an example for how to make a timer on a second thread, see here:
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();
}
}
Output:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.