Our first example demonstrates how to work with timers in Java. We’ll explore how to schedule tasks to be executed at a future time or repeatedly at intervals.
The first timer will fire ~2 seconds after we start the program, but the second should be stopped before it has a chance to fire.
To run the program, compile and execute it:
In this Java example, we use the java.util.Timer and java.util.TimerTask classes to achieve similar functionality to Go’s timers. The Timer class is used to schedule tasks (represented by TimerTask objects) for future execution.
We create two timers:
The first timer is scheduled to run after 2 seconds and simply prints a message.
The second timer is scheduled to run after 1 second, but we cancel it immediately after scheduling.
We use Thread.sleep() to pause the main thread, allowing time for the timers to potentially fire. This is equivalent to the time.Sleep() function in the original example.
Note that in Java, we need to explicitly clean up the timers by calling cancel() on them when we’re done. This is not necessary in Go due to its garbage collection mechanism.