I am making an Android App that at some activity shows a timer with hours minutes and seconds. As seconds value will update every second, I was thinking to make a thread with 1000 ms sleep, after each cycle it will add 1 to seconds and update the text view. Accordingly it will calculate minutes and hours and update the respective text views.
But I have one doubt in mind, are threads reliable enough to accomplish such a task or should I use inbuilt library function to get seconds after every cycle ? I am a little concerned about getting my timer getting out of sync if I rely completely on thread to calculate time.
On a multiprocessor system, multiple threads can concurrently run on multiple CPUs. Therefore, multithreaded programs can run much faster than on a uniprocessor system. They can also be faster than a program using multiple processes, because threads require fewer resources and generate less overhead.
A single CPU core can have up-to 2 threads per core.
Second, running an excessive number of threads results in overhead due to the way they compete for limited hardware resources. It's critical to distinguish between hardware and software threads. Programs create threads, which are referred to as “software threads.” Threads on hardware are actual physical resources.
A core (CPU) in Processor will handle only one Task ( Process or Thread ) at a given time. so in Processor with 1 core will handle one thread at a time. so technically no matter how many threads you open for this processor it will serve a thread at a given time.
Sleep is not good enough.
Sleep will pause the thread for a minimum of the specified period of time, but the actual sleep period may be longer than the specified time.
Use Handler. Here's a very good detailed post on that.
long startTime = 0;
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
@Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) Math.round(diff / ((double)1000));
int minutes = (int) Math.round(seconds / ((double)60));
seconds = seconds % 60;
// Use the seconds
timerHandler.postDelayed(this, 500);
}
};
Start timer-
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 0);
Stop timer-
timerHandler.removeCallbacks(timerRunnable);
On pause-
timerHandler.removeCallbacks(timerRunnable);
Sleep with 1000 ms delay is bad option, since there is always a jitter and also some CPU time is spent on execution of your routine.
I would propose to profit from ScheduledExecutorService.scheduleAtFixedRate method, that will call your implementation at fixed rate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With