One: Thread synchronization
A security issue occurs when multiple threads share data, and solving this problem requires a thread synchronization mechanism.
1. What is thread synchronization:
To resolve data sharing problems, you must use synchronization, which means that multiple threads can have only one thread executing the specified code within the same time period.
The other thread waits for this thread to finish before it can continue execution.
Lock-On, modify-and-release lock, which locks the resource before any thread modifies the specified resource and cannot be modified by other threads during the lock
Resource, the thread frees the lock on the resource when the thread is modified, guaranteeing that the concurrent thread has only one thread at any one time
You can work with shared resources.
2.2 ways to Thread Sync:
(1) Synchronizing code blocks
Synchronized (the object to synchronize) {
The operation to synchronize;
}
(2) Synchronization method
Public synchronized void Method () {
The operation to synchronize;
}
Usage principle: If all code needs to be synchronized, use the synchronous method, or use a synchronous code block.
3. Synchronization criteria:
Thread synchronization can cause performance degradation, but it must be synchronized to improve data security. The synchronization criteria are as follows:
(1) Do not synchronize all methods, put code that does not need to be synchronized outside the code block.
(2) do not block, such as IO operation
(3) Do not call other synchronization methods when holding the lock, otherwise it will cause thread deadlock
(3) A single-threaded environment uses threads that are unsafe to ensure performance, multithreaded environments using thread-safe.
4. Thread Deadlock:
A deadlock occurs when two threads wait for each other to release the Sync Monitor, the Java Virtual machine is not monitored, and no action is taken to handle the deadlock
Situations, you should take steps to avoid deadlocks when you are programming multithreading. Once a deadlock occurs, the entire program does not have any exceptions or
Any hint, except that all threads are in a blocked state and cannot continue.
In multi-threading to share resources, synchronization is required, but too much synchronization can cause deadlocks.
Multithreading (three) thread synchronization