There are two problems:
- The timer continues to work if not stopped.
- The static variable count is not synchronized between threads.
Check out this explanation from Gray about synchronization between threads: Static variables and multithreading in java. It explains that each thread has its own copy of the static variable. To avoid this, declare a volatile variable.
For simple testing like this example, you will need a volatile variable. For critical situations, when you need real-time synchronization between threads, use AtomicInteger.
private static volatile int count;
Be sure to stop the timer using the timer.stop () function. Incorrectly adding Thread.sleep to the loop, this protects the CPU resources and allows thread synchronization for non-volatile variables.
while (count < 5) { Thread.sleep(10); } timer.stop();
You can find out more about the difference between a variable and AtomicInteger here: What is the difference between atomic / mutable / synchronized?
source share