1. Why mutual exclusion is required:
? The mutex operation guarantees the atomicity of multi-threaded operation, The mutex semantics of Java are provided by the Synchronized keyword. There are two main ways of synchronizing code block and synchronous method |
2. Integer self-increment operation
Common Thread-safety issues: Read data from memory to register,<---into a thread From Register +1 Write memory such as this is not an instruction to complete the operation, and there are multiple threads operating uniform resources, to ensure that the above three steps are executed one time, without being disturbed by other threads (atomicity: Either do not execute, or all execute) |
3. Waiting for a thread
Thread.Join ();: The main thread in Java waits for the end of another thread by default The role of Start () is to start a thread that divides the thread flow at the call The join () method, in contrast, enables the two execution processes to be merged into one |
4. Synchronization
Synchronization is a time-series relationship to ensure that two thread events are executed Calls that support synchronous operations are called synchronization primitives, including: mutexes, conditional variables, semaphores, mailboxes, event flags, spinlock, and so on
Wait () Waits for notification, and the call blocks the current thread.
Notify () notifies that if more than one thread is blocked on the obj, the call wakes up one (blocking) thread waiting for the obj.
Notifyall () notifies that if more than one thread is blocked on the obj, the call wakes up all (blocking) threads waiting for the obj.
|
5. Signal loss
| Wait/notify/notifyall provides a way for inter-thread event notification, but this notification cannot be effectively "remembered", so there is a possibility of a notification loss (notify missing)-the line enters upgradeable notify to send the notification, Wait after the thread receiving the notification, at which point the prior notification is lost. The POSIX specification is called signal loss, since most operating systems (Linux,mac,unix) now follow POSIX, so the word "signal loss" is used more broadly. |
6. False Wakeup
False Wakeup (spurious wakeup) when using conditional waits, we use a while (condition not satisfied) { condition_wait (cond, mutex);} Instead of: If (condition not satisfied) { condition_wait (Cond,mutex);}This is because there may be a false wake-up "spurious wakeup" situation. That is, even if no thread calls Condition_signal, the function that originally called condition_wait may return. At this point the thread is awakened, but the condition is not satisfied, this time if the condition is not checked and down, it may cause the subsequent processing error. |
Java multi-threaded synchronization and mutex