Concurrent access to objects and variables: multi-threaded programming

Multi-threaded programming: objects and variables concurrent access:

  1. volatile keyword
  2. synchronized synchronization method
  3. synchronized synchronized statement block

The volatile keyword:
The main role of the volatile keyword is to make visible the variables between multiple threads.
If the case is not multiple inheritance, use inheritance Thread class and Runnable interface to achieve the results achieved in the running and there is no much difference. If the problem occurs once the case of multiple inheritance, the way Runnable interface to achieve multi-threading is necessary.
Under normal circumstances the value of the variable is read from the work memory, different thread will read from different working memory, the stack if you want to access the public to read the data, it must be read from the common memory variables by using the keyword Volatie force value, increases the visibility of instance variables between multiple threads.
However, the most fatal disadvantage volatie atomic keywords are supported, for example, i = i + 1; such an operation is not an atomic operation, it is not thread safe.
AtomicInteger can be done in the absence of a thread-safe lock case. Atomic class is not completely safe, we need to use synchronized when necessary to resolve the call between the methods.

Synchronized
two threads access method that is not synchronized, if multiplied by two simultaneous operation of the business object instance variables, it is possible to "non-thread-safe" problem, you can add synchronized.
Keyword synchronized statement calling the method must be queued to run, in addition to sharing the word to keep in mind that only read and write access to shared resources it needs synchronization, if not shared resources, there is no need for synchronization.

Low efficiency drawbacks synchronization method, so that the use of synchronized sync block, half synchronous, asynchronous half.

When synchronization synchronized (non this object x) sync block format, the object monitor must be the same object, if not the same object's monitor, the operation result is an asynchronous call,
static synchronized with the synchronized method synchronized (class) block:
keywords can also be used on static static method, if written, that is, the current class of class * .java files corresponding to be holding locks, and added to the non-target approach is to target locked.

Multithreading deadlock (deadLock):
Deadlock is a program designed Bug, will be used in the design process to avoid the two sides hold each other's locks.

Published 14 original articles · won praise 0 · Views 204

Guess you like

Origin blog.csdn.net/weixin_43237071/article/details/104033505