Java Multi-Threading security issues:
Because there may be shared resources in a multithreaded code block, when a thread is using a shared resource, the CPU causes the threads to be hoisted and instead executes another thread, and the second thread uses the shared resource, causing an error to occur when the shared resource is inconsistent.
Java provides a solution for synchronizing blocks of code, which is a good solution to this problem.
Synchronized (object)
{
Accessing shared resource Codes
}
The parameter object can make any object, acting like a switch, when the current thread executes into a synchronous code block, it will first determine the state of the object, if the synchronization code block is not executed by a thread, into the code block, and also set the object's flag bit, to synchronize the code block execution is complete, Set the object's flag bit again to end execution. If a block of code is executed by a thread, the execution of the CPU is discarded directly. An object acts like a lock.
Disadvantages of synchronizing code block schemes:
Multiple threads need to determine the lock and consume more resources.
"Java Learning" Multithreading 2