[Java] Java synchronized keyword explanation

Source: Internet
Author: User

The Java language keyword, which can be used to lock objects and methods or blocks of code, when it locks a method or a block of code, at most one thread at a time executes the code. When two concurrent threads access the same object in the same lock 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. However, when a thread accesses one of the lock code blocks of object, another thread can still access the non-locking code block in the object.

One, synchronized synchronization method

1.synchronized synchronization method, for object lock

 Public classExceptionreleaselock { Public  synchronized  voidtestlockexception () {if(Thread.CurrentThread (). GetName (). Equals ("A") {System.out.println ("Thread Name:" +thread.currentthread (). GetName () + "Start run time:" +System.currenttimemillis ());  for(inti=0;i<200;i++){                 while(i>20) {System.out.println ("I=" +i); Integer.parseint ("ABCD"); }            }        }Else{System.out.println ("B Thread Run Time:" +System.currenttimemillis ()); }    }}

2.synchronized Lock re-entry

When a thread requests an object lock held by another thread, the thread blocks, and when the thread requests a lock on an object held by itself, if the lock is a re-entry lock, the request succeeds or is blocked.

Let's take a look at synchronized, which has a built-in locking mechanism that enforces atomicity, is a re-entry lock, so when using synchronized, when a thread requests an object lock and then requests the object lock again, the object lock can be obtained again. This means that when a synchronized method/block is called inside the other synchronized methods/blocks of this class, it is always possible to get the lock. Otherwise, it will cause a deadlock.

/*** Created by Administrator on 2015/12/30 0030. * Lock re-entry mechanism*/ Public classLocksyn { Public synchronized  voidA () {System.out.println ("A ()");    b (); }     Public synchronized  voidB () {System.out.println ("B ()");    C (); }     Public synchronized  voidC () {System.out.println ("C ()"); }}
 Public class Testlocksyn {    publicstatic  void  main (string[] args) {          New Locksyn (). A ();    }}

Output Result:

A () b () C ()

When there is an inheritance relationship, subclasses can invoke the synchronization method of the parent class through a reentrant lock.

 public  class   Animal { public  void   Eat () {System.out.println (         "Animal Eat Foods" );  try   {Thread.Sleep ( 3000);  catch   (Interruptedexception e) {e.        Printstacktrace (); }    }}
 Public class extends   Animal {   synchronizedpublic    void  eatfish () {       System.out.println ("Cat eatfish ...");        Try {           Thread.Sleep (+);             This . Eat ();        Catch (interruptedexception e) {           e.printstacktrace ();    }}}

Test:

 Public class Testanimal {    publicstatic  void  main (string[] args) {        New Cat ();        Cat.eatfish ();    }}

Output:

Cat Eatfish ... Animal Eat foods

Let's take a look at how the entry lock implements Reentrant, which is implemented by associating a thread holder and a counter for each lock, indicating that the lock is not held by any thread when the counter is 0, and that any thread may acquire the lock and invoke the appropriate method; When a thread request succeeds, the JVM will note the lock's holding threads , and the counter is set to 1, when another thread requests the lock, it must wait, and the thread holding the lock, if requested again, can get the lock again, the counter will increment, and when the thread exits the synchronization code block, the counter decrements, and if the counter is 0, the lock is freed.

3. Exception occurred, lock automatic release

 Public classExceptionreleaselock { Public  synchronized  voidtestlockexception () {if(Thread.CurrentThread (). GetName (). Equals ("A") {System.out.println ("Thread Name:" +thread.currentthread (). GetName () + "Start run time:" +System.currenttimemillis ());  for(inti=0;i<200;i++){                 while(i>20) {System.out.println ("I=" +i); Integer.parseint ("ABCD"); }            }        }Else{System.out.println ("B Thread Run Time:" +System.currenttimemillis ()); }    }}

 public  class     ExceptionReleaseThread1 extends   Thread {  private   Exceptionreleaselock    Exceptionreleaselock;  public   ExceptionReleaseThread1 ( Exceptionreleaselock lock) { this . Exceptionreleaselock=lock; } @Override  public  void   run () {exceptionreleaselock.testlockexception (); }}
 Public class extends   Thread {    private  exceptionreleaselock exceptionreleaselock;      Public ExceptionReleaseThread2 (Exceptionreleaselock lock) {        this.exceptionreleaselock=  lock;    }    @Override    publicvoid  run () {       exceptionreleaselock.testlockexception () ;    }}

Test:

/*** Created by Administrator on 2015/12/30 0030. * * After an exception occurs, the lock is automatically released*/ Public classTestexceptionrelease { Public Static voidMain (string[] args) {Exceptionreleaselock lock=NewExceptionreleaselock (); ExceptionReleaseThread1 a=NewExceptionReleaseThread1 (lock); ExceptionReleaseThread2 b=NewExceptionReleaseThread2 (lock); A.setname (A); B.setname (B);        A.start ();    B.start (); }}

Output Result:

A thread has released a lock after an exception has occurred, and thread B executes normally.

4. Synchronization does not have inheritance.

 Public class extends   Animal {      @Override    public  void  eat () {        System.out.println ("nosynchronized ....");}    }

You need to add synchronized synchronization before the method.

Second, synchronized synchronous statement block

[Java] Java synchronized keywords

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.