Implementation principle and application of Java synchronized

Source: Internet
Author: User

Synchronized in multi-threading should be the most we use, and many people will call it a heavyweight lock. Each object in Java can be used as a lock. It is shown in the following three forms.

For the normal synchronization method, the lock is the current instance object.

Book class Books {private int id;//book idprivate String name;//book name private int number;//book Quantity//Depository public void Stockbooks (i NT count) {number+=count;try {thread.sleep},} catch (Interruptedexception e) {e.printstacktrace ();}} Borrow public void taskbooks (int count) {number-=count;try {thread.sleep ()} catch (Interruptedexception e) { E.printstacktrace ();}}
We first declare the object of a book, and then simulate a library book library of the scene;

Library class Bibliotheca implements Runnable {private Books books;public Bibliotheca (Books Books) {super (); this.books = Boo KS;} Public Books Getbooks () {return Books;} public void Setbooks (Books Books) {this.books = Books;} @Overridepublic void Run () {books.stockbooks (1000);//Deposit 1000 Books books.taskbooks (1000); System.out.println (Thread.CurrentThread (). GetName () + ":" + books.getnumber ());}}

First try not to lock what is the result;

public static void Main (string[] args) {Books Books = new Books ("Golden Bottle Plum", 1000);//initial deposit 1000 principal bottle Plum Bibliotheca Bibliotheca = new Bibliotheca (books); To inject books into the library Thread threads[] = new THREAD[10]; Simulates 10 threads for (int i = 0; i < i++) {threads[i] = new Thread (Bibliotheca, "thread" + i); Threads[i].start ();}}

I ran 5 times and found that the final result for each thread was the same after each execution, such as 10 1000, or 10 2000, including 3000,4000,5000. So the result is certainly not correct, we put a lock on this object and try again;

@Overridepublic void Run () {synchronized (books) {books.stockbooks (1000);//Deposit 1000 Books books.taskbooks (1000); System.out.println (Thread.CurrentThread (). GetName () + ":" + books.getnumber ());}}
The end result is 1000, so this is the result we want;

When multiple concurrent threads access the same object in the synchronized (this) synchronization code block, only one thread can be executed within a single time. The other thread must wait for the current thread to finish executing the block before it can execute the code block. In the Run method, we used the synchronized (books) method to lock the object.

When there is no explicit object as a lock, just want to synchronize a piece of code, you can create a special object to act as a lock:

@Overridepublic void Run () {synchronized (this) {books.stockbooks (1000);//Deposit 1000 Books books.taskbooks (1000); System.out.println (Thread.CurrentThread (). GetName () + ":" + books.getnumber ());}}
such as above, is not very common;

Private byte[] lock = new Byte[0];  Special instance variable public   void method ()   {      synchronized (lock) {         //Todo Synchronous code block      }   }   Public void Run () {   }

A 0-length byte array object will be more economical to create than any object-look at the compiled bytecode: generate a 0-length byte[] object with only 3 opcode, and object lock = new Object () requires 7 lines of opcode. for a static synchronization method, the lock is the class object of the current classes. We know that static methods do not belong to an object, but rather belong to a specific class, so we have to lock as follows;
Class Countthread extends thread{   private static int count;   Public Countthread () {      count = 0;   }   Public synchronized static void method () {for      (int i = 0; i < 5; i + +) {         try {            System.out.println (thread.c Urrentthread (). GetName () + ":" + (count++));            Thread.Sleep (+);         } catch (Interruptedexception e) {            e.printstacktrace ();}}   }   public void Run () {      method ();   }}
Note that I do not have a synchronous lock on the Run method, because I want to synchronize only method () this specific way;
public static void Main (string[] args) {countthread countthread=new countthread (); Thread threads[] = new THREAD[10]; Simulates 10 threads for (int i = 0; i < i++) {threads[i] = new Thread (countthread, "thread" + i); Threads[i].start ();}}
Now let's change this example:

Class Countthread extends thread{   private static int count;   Public Countthread () {      count = 0;   }   Public synchronized static void method () {for      (int i = 0; i < 5; i + +) {         try {            System.out.println (thread.c Urrentthread (). GetName () + ":" + (count++));            Thread.Sleep (+);         } catch (Interruptedexception e) {            e.printstacktrace ();}}   }   Public  static void Method1 () {for      (int i = 0; i < 5; i + +) {         try {            System.out.println (Thread.curre Ntthread (). GetName () + ":" + (count++));            Thread.Sleep (+);         } catch (Interruptedexception e) {            e.printstacktrace ();}}   }   public void Run () {      method ();      Method1 ();   }}
The Run method has the method () and the Method1 (), and the result is that the synchronization lock will be kept in sync, but the synchronization lock will appear chaotic data;

What if our method () and method1 () do not add synchronization and want to synchronize the two methods? This is the third form we want to say;

For synchronous method blocks, the lock is an object configured in synchonized brackets.

  Public synchronized void Run () {      method ();      Method1 ();   }
Of course you can do the same:

public void Run () {synchronized (this) {method (); Method1 ();}}
Isn't it amazing!

A method of writing a modifier, the second modifier is a code block, but the wording of the two is equivalent, are locked the whole method of content. When a thread view accesses a synchronous block of code, it must first get a lock, exit or throw an exception when the lock must be released, so where does the lock exist? What information is stored inside the lock? Please listen to the next explanation!


Implementation principle and application of Java synchronized

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.