Java review-multi-threaded synchronization

Source: Internet
Author: User

1, the problem leads

In a multithreaded environment, there may be multiple threads accessing a limited resource (resource sharing) at the same time, in order to avoid resource access, operation confusion, so there is a mechanism for locking! Reasonable control of the operation of resources (read and write) permissions.


2. Understand several concepts

1) Get CPU resources: The thread wants to execute must get CPU resources, this is a necessary condition! However, the scheduling of resources is based on the priority of the thread, the use of thread resources and other factors to determine the operating system. No need to drill down, just know that the thread wants to run must get to the CPU resources, this is a threshold. We always tangled Thread of sleep, yield, start after exactly when to run, in fact, is the CPU resource competition, who get who will run!

2) Gets the object lock: in Java, the lock management of an object is accomplished through synchronized and contention. It must be noted here that ! For the locked object, all of his other locked parts are only allowed to lock the thread to execute, after the completion of the automatic release of the lock, and then the subsequent threads continue to compete for the lock, so the lock equivalent is synchronous operation mechanism. The identity that obtains the lock is whether the thread executes into the code identified by the Synchronized keyword, either as a method or as a block of code. For those who do not acquire the lock and want to compete for the lock of the thread can only wait, but the waiting process is actually blocked in the lock pool, until the lock to jump out of the pool, after jumping out is not immediately executed, but another threshold, competing CPU resources. It's always been a tangle of threads. Does the thread execute until it runs through the synchronized code block? In fact, synchronized is only an object lock owned, in the process of execution is also at any time by the operating system scheduling and loss of CPU resources, from the operational state to ready State! Until the next time the CPU resource is acquired to continue execution, it is no different from the previous. Here you have to distinguish between that is  sleep, yield, they are all related to the threshold of CPU resource competition, for the concept of locks, It has nothing to do with them, meaning that they do not affect the current thread's hold and release of the lock.

3) Wait and wake up: Wait (wait) and wake (notify) is actually a communication between multithreading, but this communication is based on the lock, that is, the precondition is that the thread owns the lock of the object! wait and wake are always paired, when a thread executes in a synchronized block of code, of course, he must have acquired the lock on the object obj, and then, because of some logical judgment that he is temporarily unfit to continue running, he invokes the wait method of obj. Wait for the right opportunity to continue, this time he is blocking in the synchronized code block, wait for the line code after the code is temporarily not executed, more deep point he is blocking in the wait pool, waiting for obj.notify to wake up! In the process of waiting he releases the held obj lock, allowing the thread in the lock pool to acquire the lock and then execute the synchronized block if the executing thread discovers that the logical condition at this time has satisfied the execution of the blocking thread. Then he is called Obj.notify to wake up, but you do not forget that the call notify is also in the synchronized block, he did not release the lock, he is only responsible for waking the wait pool thread, he must execute the synchronized block after the real release of the lock! Here the threads in the wait pool compete for three things in order to really make threads from the wait pool--"lock pool--" runnable--"Running

One is: so many threads in the pool who are awakened in the end?

The second is: How do I and the thread in the lock pool continue to grab the lock of the object after awakening?

The third is: how can I compete with other threads for CPU resources after acquiring a lock?

Report:


3, Synchronized

1) synchronized keyword, which consists of two usages: Synchronized method and synchronized block.

2) When the Synchronized keyword modifies a method, this method is called the synchronous method. When the Synchronized keyword modifies a piece of code, this code is called a synchronous block of code.

3) Each object in Java has a unique lock (lock or monitor), and when a thread accesses an object's synchronized method, it means that the object is locked, and no other thread can access the Synchronized method at this time. , until the previous thread executes the method (or throws an exception), then the thread will release the lock on the object and other threads will be able to access the Synchronized method. ( Remember that locks are objects, not methods, objects are the minimum granularity of locks, so methods that are identified for the same lock cannot be performed concurrently by multiple threads, because only the thread that owns the lock can execute )

Note There are two objects: one is a thread object, one is an object with a method identified by the synchronized, and the two may be the same object, generally not.

4) If an object has more than one synchronized method, and a thread has entered a synchronized method at some point, the other thread is not able to access any synchronized method of the object until the method has finished executing, because Synchronized as a token of a method but he locks the method to the instance itself.

5)synchronized static modifier, then the lock is not the current object, but the current object's class object , we know that the class object is unique, that is to say that multiple instances share a class object, In this way, all methods for synchronized static modification will only allow one thread to access it.

6) synchronized (OBJ) block, which indicates that the thread will lock the Obj object at execution time, then only one thread is allowed to enter the block at once, the key is which object to lock, the scope of the lock, and when to release the lock. In addition, it is recommended to use the synchronized block instead of the synchronized method identification, because the synchronized block more granular control lock! And this lock-on object, obj, can be defined arbitrarily, and we'd better customize a

Private Object obj = new object; The advantage is that it is not rigidly tied to the current instance itself, if the synchronized adornment method is the current instance itself.

7) If the lock of an object is found before executing the synchronized code block, then the thread can only wait for the lock to be freed before it can continue execution, at which point the current thread is blocked, that is, waiting for the lock of the object in the lock pool.

8) If the current thread in the synchronized code block invokes the wait method of the locked object, then the current thread is equivalent to blocking itself in the wait pool while releasing the lock on the object. At this point, another thread with a lock is required to execute notify in the synchronized code block, and execution notify does not release the lock, but he can wake the thread in the wait pool and have permission to continue to grab the object lock. So wait and notify are paired in the same synchronized block.


4, the problem that synchronized leads

Whether you will encounter this situation: there is a method, he is synchronous, but he is more time-consuming, when there are 10 threads need to access this method, then the tenth thread estimated to wait a long time to execute, if it is 100? What if it's a 1000? If it is a high-traffic page, the problem is obvious, in this case, synchronized does not solve the way, can only wait to execute, perhaps the program will eventually end up memory overflow.


5, 1.5 of concurrent packages

java.util.concurrent.*

He can solve the problem of synchronized, but also a layer of packaging for threading, his appearance is enough to show that the use of thread in the business is difficult.

About 1.5 of concurrent packages need to continue to learn, especially the inside of the atomic operation needs to go deep, now the purpose of only the thread of the basic knowledge over!


6, inter-thread communication

1) wait and notify are both methods of the final type of object and cannot be overridden, but can be inherited.

2) The biggest role of wait and notify is to collaborate between threads;synchronized blocks are only for wait and notify services

3) The precondition of calling wait and notify is that the lock of the object must be owned, then the call to wait must be in the synchronized block, and the lock of the current object will be released after the call to wait, that is, the lock of the synchronized block is released. Other threads can enter this synchronized block until other threads call notify in the synchronized block, After the current thread that calls wait is awakened (all threads that have called wait are randomly awakened) also continue to compete for locks (provided that the thread that called notify has freed the lock on the object), the lock competes and the CPU resource is in the running state.

4) Another method that causes thread pauses is the sleep method of the thread class, which causes the thread to sleep for a specified number of milliseconds, but the thread does not release the lock on the object during sleep, which means that he will compete with other threads for CPU resources as soon as the sleep time has elapsed!

5) with an example of adding one and minus one, the requirement is not to allow number only in [0,1]

 private int number = 0  ; public synchronized int increase () {  while (number != 0) {    try   {    wait ();    }   catch   (interruptedexception e)    {    e.printstacktrace ();    }  }  number++;  notify ();  return number; }   public synchronized int decrease () {  while (number == 0) {    try   {    wait ();   }   catch  ( interruptedexception e)    {    e.printstacktrace ();    }   }  number--;  notify ();   return number; } 


7. Waiting pool and lock pool

1) Waiting pool: That is, the wait pool, when the thread executes the wait method of the lock object in the synchronized code block, the thread is blocked in the wait pool. The method of waking him is to execute the lock object notify by calling interrupt of the current thread or another thread in the synchronized code block.

2) Lock pool: When a thread finds that the lock of an object has been fetched before executing the synchronized code block (that is, the code thread is executing), it can only wait for the lock to be freed before it can continue execution, at which point the current thread is blocked in the lock pool. Until the end of synchronized block execution, there is a chance to new competition lock.


8. Producer Consumer model

Producers and consumers do not communicate with each other directly, and through the blocking queue to communicate, so producers do not have to wait for consumer processing after the production of data, directly to the blocking queue, consumers do not find producers to data, but directly from the blocking queue, the blocking queue is equivalent to a buffer, Balance the processing power of producers and consumers.

Multi-threaded in the famous design pattern, back in-depth study supplement.


9. The problem of dining philosophers (deadlock Dead-lock)

Suppose there are five philosophers sitting around a round table, ready to eat rice, and they can only use the two chopsticks on their right and left hand side (one chopstick on each hand). philosophers never talk, and each philosopher takes his left-handed chopsticks and always waits for the right chopstick (or vice versa). Even without a deadlock, resource exhaustion can occur. For example, let's say that when a philosopher waits for another chopstick for more than five minutes, he drops the chopstick in his hand and waits five minutes for the next attempt. This strategy eliminates deadlocks (the system always goes to the next state), but there is still a possibility of a "live lock". If five philosophers enter the restaurant at exactly the same time and pick up the chopsticks at the same time, then the philosophers will wait five minutes while putting down their chopsticks, waiting for five minutes, and picking up the chopsticks at the same time.


10. Thread Group

Thread groups: All threads are part of a thread group, which can be a default thread group, or a group that is explicitly specified when a thread is created.

Note: At the beginning of the creation, the thread is restricted to a group and cannot be changed to a different group; If you create multiple threads without specifying a group, they will belong to the same group as the thread that created them.

Thread groups can be passed as parameters in the method of constructing threads, which is not to be confused with thread pool, in addition, the threads group is seldom used, so understand!


Java review-multi-threaded synchronization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.