Continue to discuss thread-safety issues in multi-window ticket sales issues:
Mode two:
Question: Is there a thread-safety issue?
Second, the cause of the problem:
When multiple statements operate on the same thread to share data, one thread executes only a portion of the statements, not finished, and another thread participates in the execution. The error that caused the shared data.
Third, the root cause of thread safety problems:
1, there are two or more than two thread objects, and there is a resource shared between threads.
2. A plurality of statements operate shared resources.
Iv. Solutions:
1, for multiple operations to share data statements, can only make a thread all run out. During execution, other threads may not participate in execution.
2. Solution to Thread-safety problems: Sun provides a thread synchronization mechanism for us to solve such problems.
Five, the Java thread synchronization mechanism in the way:
1. Sync code block:
1 The format of the synchronized code block:
Synchronized (lock object) {
code that needs to be synchronized ...
}
objects are like locks. A thread holding a lock can be executed in synchronization.
A thread that does not hold a lock cannot go in even if it acquires the execution power of the CPU because the lock is not acquired.
2 The synchronization code block to note the matter:
A any object can be used as a lock object.
b The Sleep method called in the synchronized code block does not release the lock object.
c The synchronization code block is used only when there is a real thread safety problem, otherwise it can be inefficient.
D The lock object of a multithreaded operation must be unique and otherwise invalid.
Six, the premise of synchronization:
1, must have two or more than two threads.
2, must be multiple threads to use the same lock.
you must ensure that only one thread in the synchronization is running.
Vii. advantages and disadvantages of synchronizing code blocks:
Benefits: Solves the problem of multithreading security.
Disadvantages: Multiple threads need to determine the lock, more consumption of resources.