Timing in Java?

Caporegime
Joined
12 Mar 2004
Posts
29,962
Location
England
I need to create a method that will update the petrolpump display in real time, ie adding another litre of petrol a second to the amount dispensed for that session and then calling the method to display the total. But how do I time it correctly? Do I use a thread or is there a better way?
 
Last edited:
Try something like this

Code:
public void refreshTime(){
		new Thread(new Runnable(){
			public void run(){
				while (flag == false){
					*Increment operations in here*
					}
					try{
						Thread.sleep(1000);
					}catch (InterruptedException e){
						
					}
				}
			}
		}).start();
	}
 
I'd consider using an Observer to maintain loose coupling, but that's probably uneccessary for your practical :)

And yes, use Threads, and update the thread everytime there is an update to be made (i.e. when an extra unit of fuel has been transfered, you'll want to update the counter display)
 
Use a Timer from the swing package, then action stuff on the events it generates rather than creating a thread and sleeping it. Also put all your gui creation stuff onto Swing's event dispatch thread.
 
Back
Top Bottom