Java Foundation Enhancement Concurrency (iv) Synchronized keywords

Source: Internet
Author: User
Tags thread class

Concurrent Series Reference article http://www.cnblogs.com/skywang12345/p/3323085.html#3907193

Synchronized principle

In Java, each object has and has only one synchronization lock. This also means that the synchronization lock is dependent on the object and exists.
When we call the synchronized method of an object, we get the synchronization lock for that object. For example, synchronized (obj) acquires a synchronous lock on the object "obj".
The access of different threads to the synchronization lock is mutually exclusive. that is, at some point in time, the object's synchronization lock can only be obtained by one thread! With a synchronous lock, we are able to implement mutually exclusive access to the object/method in multiple threads. For example, there are now two threads A and thread B, all of which access the synchronization lock for object obj. Suppose, at some point, thread a acquires the "synchronous lock of obj" and performs some action, and at this point, thread B also attempts to acquire "the synchronous lock of obj"--thread B Gets the failure, it must wait until thread a releases "the object's synchronization lock" and thread B gets to "Obj's synchronous lock" So that they can run.

synchronized Basic Rules

First: When a thread accesses the "synchronized method" or "Synchronized code block" of "an object", other threads will block access to the "synchronized method" or "Synchronized code block" of the object.
Second: When a thread accesses the "synchronized method" or "Synchronized code block" of an object, other threads can still access the non-synchronized code block of the object.
Article three: When a thread accesses the "synchronized method" or "Synchronized code block" of an object, other threads ' access to other "synchronized methods" or "synchronized code blocks" of the object is blocked.

First article

Myrunnabletest.java source Code, Note: This is the implementation of Runnable interface

1  PackageCom.thread;2 3 classMyrunnableImplementsrunnable{4     5 @Override6      Public voidrun () {7         synchronized( This) {8             Try {  9                  for(inti = 0; I < 5; i++) {TenThread.Sleep (100);//Sleep 100ms OneSystem.out.println (Thread.CurrentThread (). GetName () + "loop" +i);  A                 } -}Catch(Interruptedexception IE) { -             } the         }   -     } -      - } +  -  Public classMyrunnabletest { +  A      Public Static voidMain (string[] args) { atRunnable demo =NewMyrunnable ();//new "Runnable object" -  -Thread T1 =NewThread (demo, "T1");//new "Thread T1", T1 is based on the demo runnable object -Thread t2 =NewThread (demo, "T2");//new "Thread T2", T2 is based on the demo runnable object -T1.start ();//start "Thread T1" -T2.start ();//start "Thread T2" in     } -  to}
View Code

Run results

T2 Loop 0123401234
View Code

Result Description :
The synchronized (this) code block exists in the run () method, and both T1 and T2 are based on the thread created by the demo Runnable object. This means that we can treat this as a "demo Runnable object", so threads t1 and T2 share "demo object's Sync lock" synchronized. Therefore, when one thread is running, another thread must wait for the "running thread" to release the "Demo Sync lock" before it can run.

Mythreadtest.java source Code, Note: This is the inherited thread class

 PackageCom.thread;classMyThreadextendsthread{ PublicMyThread (String name) {Super(name); }         Public voidrun () {synchronized( This) {            Try {                   for(inti = 0; I < 5; i++) {Thread.Sleep (100);//Sleep 100msSystem.out.println (Thread.CurrentThread (). GetName () + "loop" +i); }            } Catch(Interruptedexception IE) {} }}} Public classMythreadtest { Public Static voidMain (string[] args) {Thread T1=NewMyThread ("T1");//new "Thread T1", T1 is based on the demo runnable objectThread t2 =NewMyThread ("T2");//new "Thread T2", T2 is based on the demo runnable objectT1.start ();//start "Thread T1"T2.start ();//start "Thread T2"    }}
View Code

Run results

T1 Loop 0011223344
View Code

Result Description :
If the result is not surprising to you, then I believe you have a deep understanding of synchronized and this. If not, please continue reading the analysis here.
The This in synchronized (this) refers to the current object, which is the current class object, which is the class in which synchronized (this) resides. Its purpose is to obtain the "synchronization lock for the current object".
For Mythreadtest.java, this in synchronized represents the Mythread object, while T1 and T2 are two different mythread objects, so t1 and T2 are executing synchronized (this ), a synchronization lock is obtained for a different object. For Myrunnabletest.java pairs, this represents the Myrunable object, T1 and T2 together a Myrunable object, so a thread acquires the object's synchronization lock. Causes a second thread to wait.

Java Foundation Enhancement Concurrency (iv) Synchronized keywords

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.