Java synchronized keyword for thread synchronization mutex

Source: Internet
Author: User

Java synchronized keyword for thread synchronization mutex

Java multi-threaded programs are now very common. Like the database operating system, multiple threads share a heap memory. If you do not control them and do not synchronize them between threads, it will cause data confusion.

Let's take a look at the following program:

 

Public class TestSynchronized implements Runnable {Timer timer = new Timer (); public static void main (String args []) {TestSynchronized test = new TestSynchronized (); thread t1 = new Thread (test); Thread t2 = new Thread (test); t1.setName ("t1"); t2.setName ("t2"); t1.start (); t2.start ();} public void run () {timer. add (Thread. currentThread (). getName () ;}} class Timer {private static int num = 0; public void add (String name) {// synchronized (this) {// not synchronized, the number of num is not normal. num ++; try {Thread. sleep (1);} catch (Exception e) {} System. out. println (name + ", you are the" + num + "thread using timer ");//}}}
Output result:

 

T1, you are the first thread to use timer
T2, you are 2nd threads using timer

Num is 2 twice. Here it is obvious that the two threads alternate when accessing the num variable of the same Timer object, so the final printing time is 2;

How can we implement mutual access to this num between different threads? We can use synchronized to synchronize code blocks, and use synchronized (this) {} to enclose the synchronization code blocks.

Output normal results:

T2, you are 1st threads using timer
T1, you are the first thread to use timer

 

Another use of synchronized is the synchronous method, which is to add the modifier synchronized before the method. When different threads access the synchronized Method of the same object, they are mutually exclusive for synchronization.

The following is a typical production consumer model code:

 

Public class TestSynchronized {public static void main (String [] args) {SyncStack ss = new SyncStack (); Producer p = new Producer (ss ); consumer c = new Consumer (ss); Thread tp = new Thread (p); Thread tc = new Thread (c); tp. start (); tc. start () ;}} class Bread {int id; Bread (int id) {this. id = id;} public String toString () {return "Bread:" + id;} class SyncStack {int index = 0; Bread [] breads = new Bread [6]; public synchronized void push (Bread B) {if (index = breads. length) {// note that if can only be used while cannot be used; Because wait will exception try {this. wait (); // the thread that accesses the current object wait ()} catch (InterruptedException e) {e. printStackTrace () ;}} this. Y (); breads [index] = B; index ++; System. out. println ("produced:" + B);} public synchronized Bread pop () {if (index = 0) {try {this. wait (); // when wait is used, the lock is no longer owned by this thread, but sleep has a lock} catch (InterruptedException e) {e. printStackTrace () ;}} this. Y (); // wake up a thread index --; System. out. println ("consumed:" + breads [index]); return breads [index] ;}} class Producer implements Runnable {SyncStack ss = null; Producer (SyncStack ss) {this. ss = ss;} public void run () {for (int I = 0; I <20; I ++) {Bread B = new Bread (I); ss. push (B); // System. out. println ("produced:" + B); try {Thread. sleep (int) Math. random () * 1000);} catch (InterruptedException e) {e. printStackTrace () ;}}} class Consumer implements Runnable {SyncStack ss = null; Consumer (SyncStack ss) {this. ss = ss;} public void run () {for (int I = 0; I <20; I ++) {Bread B = null; B = ss. pop (); // System. out. println ("consumed:" + breads [index]); // if it is put here, there will be a problem. The consumption value is 0 first, and then the production value is 0try {Thread. sleep (int) Math. random () * 1000);} catch (InterruptedException e) {e. printStackTrace ();}}}}

The push and pop methods of the synchronized stack object SyncStack are the synchronization methods. The producer thread and consumer thread will access the pop and push methods.

 

 

The following describes the implementation of this synchronization mechanism. Java assigns a unique object lock to each class object, and each thread needs to obtain the lock to access the members of this object (of course, this refers to the thread to be synchronized ). Because an object has only one object lock, after a thread obtains the lock, the other thread accessing the same object must wait until the former executes the lock and release the object lock to achieve mutual exclusion. That is to say, synchronized is for objects, not classes. Look at the figure above. ObjectA and ObjectB are different instances of the same class, so ThreadAn and ThreadBn are irrelevant. Only ThreadA1234 is synchronized, as is ThreadB1234. In addition, non-synchronized methods and code blocks are not affected and are not mutually exclusive.

Does it implement synchronization at the class level? Yes. In Java, not only are class instances, but each class also corresponds to a lock. In this way, we can declare the static member function of the class as synchronized, to control its access to static member variables of the class. The Synchronous Code block is synchronized (classname. class ){}

The final summary is from http://www.cnblogs.com/devinzhang/archive/2011/12/14/2287675.html:

1) In an object instance, synchronized aMethod () {} can prevent multiple threads from simultaneously accessing the synchronized Method of the object (if an object has multiple synchronized methods, as long as a thread accesses one of the synchronized methods, other threads cannot simultaneously access any of this object's synchronized methods ). At this time, the synchronized methods of different object instances are irrelevant. That is to say, other threads can access the synchronized Method in another object instance of the same class at the same time;
2) is the scope of a class. synchronized static aStaticMethod {} prevents multiple threads from simultaneously accessing the synchronized static method in this class. It can work on all object instances of the class.
2. In addition to using the synchronized keyword before the method, the synchronized keyword can also be used in a block in the method, indicating that only the resources in this block are mutually exclusive. Usage: synchronized (this) {/* block */}. Its scope is the current object;
3. the synchronized keyword cannot be inherited. That is to say, the method of the base class synchronized f () {} is not automatically synchronized f () {} in the inheritance class (){}, instead, it becomes f (){}. You need to explicitly specify a method of the inherited class as the synchronized method;

Some Understanding of synchronized (this)

1. When two concurrent threads access the synchronized (this) synchronization code block of the same object, only one thread can be executed within a time period. The other thread must wait until the current thread completes the code block before executing the code block.

2. However, when a thread accesses a synchronized (this) synchronization code block of the object, the other thread can still access the non-synchronized (this) synchronization code block of the object.

3. When a thread accesses a synchronized (this) synchronization code block of the object, other threads perform synchronization on all other synchronized (this) access to the synchronization code block will be blocked.

4. The third example also applies to other synchronous code blocks. That is to say, when a thread accesses a synchronized (this) synchronization code block of an object, it obtains the object lock of this object. As a result, access by other threads to all the synchronized code parts of the object is temporarily blocked.

5. The above rules apply to other Object locks.

 

Related Article

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.