Threads are mutually exclusive to ensure that at most one thread executes the code at the same time. So what problems does it solve? Account deposits and withdrawals can only be operated by one person at the same time.
Let's look at a simple example (the problem of multithreading):
The printing results are as follows:
To solve the above problems:
Add the synchronized keyword, that is, unscramble the comment.
Print results:
Summary:
When two concurrent threads access this synchronized(this) block of synchronized code in the same object, only one thread can be executed in one time. Another thread must wait for the current thread to execute the code block before it can execute the code block. That is, when a thread accesses a synchronized(this) block of synchronized code in an object, access to all other synchronized(this) blocks of synchronized code in the object will be blocked by other threads.
Note: To be mutually exclusive, the lock must be the same. In the demo above, both threads use the same new output, so output is the same object.
See the blog for details. Synchronized threads
Brief Answer Notes:
You can see by adding the synchronized keyword. As long as m or run operates on the account, no matter how long it takes in the middle or how long it sleeps, the thread will execute this method before executing other methods. Both methods must add the synchronized keyword, and both lock the same object (the object locked here is the test object). That is to say, as long as one thread enters any locked method of the test object, the other threads can not access the method with the same lock in the object.