Multi-thread----threads mutually exclusive and renewed

Source: Internet
Author: User
Tags mutex

This article connected to a multi-thread----thread Mutex

Sorry in the previous article was meant to say that the thread mutex, the results compared to the next quartor and timer, said quartor a bit more. This section focuses on the exclusion of one thread.

Learn about thread mutexes in the following ways:

There are two ways to implement thread mutex, sychronized wait/notify Lock (read/write). Three different ways.

Start with the first use of the sychronized keyword first. We should not be unfamiliar with this, because we have written many thread-safe or thread-mutually exclusive examples, using the sychronized keyword should be the most important way, When using this keyword-modifying method or block of code, you can ensure that at most one thread at a time executes the code with an example of the code first:

This is I use the Synchronized keyword write a a hungry man-style singleton mode, here we are not to design patterns, mainly to take this as an example, to illustrate the use of synchronized this keyword.

In the above code block we can see getinstance this method is synchronized keyword modification method, in this method has a synchronized code block, here I write this is to demonstrate, In fact, getinstance this method should not add synchronized this keyword, because in the method has been used, two places add words may lead to deadlock. And then we'll talk about the parameters of the Synchronized keyword, or the lock object, which we can compare to real-life locks. This lock has two kinds of object lock is a class, in fact, the class lock is also an object lock. When a method or block of code is locked, other objects want to use the lock to find that the lock handles the locked state and he cannot access the locked content. It is only possible to get into the method when the object lock is released, thus realizing the mutex of the thread. Of course, this lock can be any other type as long as it is guaranteed to be the same lock. For example, use a string or int as long as the object can be used as a locked lock.

Let's talk about the difference between the method and the code block modified by synchronized:

1. Synchronized method : Declare the Synchronized method by adding the Synchronized keyword to the method declaration. Such as:
Public synchronized SingleTon getinstance ();
The Synchronized method Controls access to class member variables: Each class instance corresponds to a lock, and each synchronized method must obtain a lock on the class instance that invokes the method to

execution, otherwise the owning thread is blocked, and once the method executes, the lock is exclusive until the lock is released when the method returns, and then the blocked thread can obtain the lock and re-enter the executable

State. This mechanism ensures that at the same time for each class instance, at most one of its member functions declared as synchronized is in an executable state (because at most only

A lock that can obtain the corresponding instance of the class, thus effectively avoiding access violations of class member variables (as long as all methods that may access the class member variable are declared as synchronized)


In Java, not only class instances, each class also corresponds to a lock, so we can also declare the static member function of the class as synchronized to control its static

Access to the operator variable.
The flaw of the Synchronized method: Declaring a large method as synchronized will greatly affect efficiency, typically if the method run () of the thread class is declared as

Synchronized, because it has been running throughout the lifetime of the thread, will cause its call to any synchronized method in this class to never succeed. Of course we can.

To resolve the problem by putting the code that accesses the class member variable into a specialized method, declaring it as synchronized, and calling it in the main method, but Java gives us

A better solution, that is the synchronized block.
2. synchronized block : Declare the synchronized block by synchronized keyword. The syntax is as follows:
Synchronized (SyncObject) {
Code that allows access control
}
The synchronized block is a block of code in which the code must obtain the object SyncObject (as previously described, can be class instances or classes) of the lock can be executed, the specific machine

System as described above. Because it can be arbitrary code block, and can arbitrarily specify the locked object, it is more flexible.
Some understanding of synchronized (this)
First, when two concurrent threads access the same object in the synchronized (this) synchronization code block, only one thread can be executed within a single time. Another line

Process must wait for the current thread to execute this block of code before executing the code block.
Second, however, when a thread accesses one synchronized (this) of an object to synchronize a block of code, another thread can still access the non-synchronized in that object

(this) synchronizes the code block.
Third, in particular, when a thread accesses one synchronized (this) of an object to synchronize a block of code, the other thread pairs all other synchronized (this) in the object

Access to the synchronized code block is blocked.
The third example also applies to other synchronous blocks of code. That is, when a thread accesses a synchronized (this) of object to synchronize a block of code, it obtains this

The object lock of the objects. As a result, other threads are temporarily blocking access to all of the synchronization code portions of the object.

Finally, the understanding of the synchronized to understand clearly which lock is used, the lock should be kept consistent.

The above is a learning summary of the synchronized keyword to implement thread mutex.

The following begins by using wait and notify to implement mutual exclusion

Let's talk about the relationship between the two:

In Java, there are no similar methods related to PV operations, process mutexes, and so on. Java's process synchronization is achieved through synchronized (), it should be explained that the Java synchronized () method is similar to the operating system concept of the mutex memory block, in Java in the object type, all with a memory lock, After a thread acquires the memory lock, other threads cannot access the memory, enabling simple synchronization and mutex operations in Java. Understand this principle, can understand why synchronized (this) and synchronized (static XXX) difference, synchronized is to apply memory lock for memory block, this keyword represents an object of the class, So its memory lock is a mutex for the same object, and the static member belongs to the class proprietary, and its memory space is common to all members of the class, which causes synchronized () to lock the static member, which is equivalent to locking the class, that is, to implement mutual exclusion among all members of the class. Only one thread at a time can access instances of the class. If you simply want to implement a thread mutex in Java, it's enough to understand that. But if you need to wake up between threads, you need to use object.wait (), object.nofity ().

We know that the state of the thread has been created, ready to clog, stop, and several states. You can dynamically change the running state of a thread by using wait and notify in the threads ' activity. Wait and nitify are used in conjunction with synchronized. We combine a very classic face test to see how to play synchronized and wait and nitify.

The interview topic is as follows: Set up three threads, a thread prints 10 times A, a thread prints 10 times b,c thread prints 10 times C, requires the thread to run concurrently, and prints 10 times the ABC handwriting code alternately.

I think when you see this topic, if you have a good understanding of the use of wait and notify and synchronized, the idea is very simple, OK, first I write the code to see what to say.

 Public classNotifyandwaitdemoImplementsRunnable {/*** Thread Name*/    PrivateString name; /*** Previous Thread*/    PrivateObject prev; /*** Own*/    PrivateObject Self; /*** Construction Method * *@paramname *@paramPre *@param Self*/     PublicNotifyandwaitdemo (String name, object Pre, Object self) { This. Name =name;  This. prev =Pre;  This. Self =Self ; } @Override Public voidrun () {intCount = 10;  while(Count > 0) {            synchronized(prev) {synchronized(self) {System.out.print (name); Count--;                Self.notify (); } System.out.println ("Eeeee"); Try{prev.wait (); System.out.println ("Ooooooooooo"); } Catch(interruptedexception e) {e.printstacktrace (); }            }        }    }    /**     * @paramargs*/     Public Static voidMain (string[] args) {Object a=NewObject (); Object b=NewObject (); Object C=NewObject (); Notifyandwaitdemo PA=NewNotifyandwaitdemo ("A", C, a); Notifyandwaitdemo PB=NewNotifyandwaitdemo ("B", A, b); Notifyandwaitdemo PC=NewNotifyandwaitdemo ("C", B, c); NewThread (PA). Start (); NewThread (Pb). Start (); NewThread (PC). Start (); }}

The code above is understood first. Today about wait and notify combine synchronized study first come here, at night there are replace him vs Korea's 12 strong race, ready to watch the ball go. The explanation of this code and how wait,notify is combined with synchronized is the next time we talk about it.

We also learn about the rest of Lock (Read/write) in the next lecture.

Multi-thread----threads mutually exclusive and renewed

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.