A: First look at the program
Look at the results of the output:
Thread-0, you're the 2nd thread to use a timer.
Thread-1, you're the 2nd thread to use a timer.
The result is clearly problematic:
This is because two threads access the same timer object, where one thread calls the timer's Add method, num++, this time, another thread may also call the Add method, num + +, then thread 1 output, thread 2 output, the output is the same num = 2
II: Solutions
The Add method adds the synchronized keyword : public synchronized void Add (String name) {
Or inside the timer, execute the code block
Synchronized (this) { num++;try {thread.sleep (1);} catch (Interruptedexception e) {e.printstacktrace ();} SYSTEM.OUT.PRINTLN (name + ", you are the first" + num + "thread using the Timer");}
Both of these methods, the truth is one, are implemented to lock the timer object.
Java Fundamentals: Thread synchronization