1. thread security issues are caused by global variables and static variables. Thread security generally involves synchronized.
If multiple threads are running simultaneously in the process where your code is located, these threads may run the code at the same time. If the result of each running is the same as that of a single thread, and the value of other variables is the same as expected, it is thread-safe.
In other words, the interface provided by a class or program is an atomic operation for a thread or the switching between multiple threads does not lead to ambiguity in the execution result of this interface, that is to say, we do not need to consider synchronization issues.
If each thread only performs read operations on global variables and static variables without write operations, this global variable is generally thread-safe. If multiple threads execute write operations at the same time, generally, thread synchronization needs to be considered; otherwise, thread security may be affected. Therefore, thread security depends on synchronization.
2. runnable and thread are two ways to implement the thread, and there is no difference in generating dirty reads.
3. In the interface mode, a thread has a shared data member, namely:
Private int COUNT = 10;
In the inheritance mode, there is no shared member between threads, but each thread has a private member, namely:
Private int COUNT = 10;
4. Principle:
First, we need to understand the working principle of the thread. JVM has a main memory, and each thread has its own working.
Memory: When a thread operates on a variable, it must create a copy in its own working memory. After the operation, it is written to the main
Memory. When multiple threads operate on the same variable at the same time, unpredictable results may occur. According to the above explanation, it is easy to come up with the corresponding scenario.
The key to using synchronized is to establish a monitor. This monitor can be a variable to be modified or another object that you think is appropriate, such as method, and then implement thread security by locking the monitor, after obtaining the lock, each thread must complete the execution.
Load to workingmemory-> Use & assign-> store to mainmemory
To release the lock. This achieves the so-called thread security.