Java synchronized use

Source: Internet
Author: User

Java synchronized

Basically, all concurrent patterns are scenarios that use serialized shared resources when resolving thread-conflict issues. This means that only one task is allowed to access the resource at a given moment. This is typically achieved by adding a lock statement to the code, because the lock statement produces a mutex exclusion effect, which is often referred to as a mutex mechanism .

Threads are clustered in front of shared resources, not queued, and can provide advice on thread scheduling through yield () and setpriority () , but these recommendations may not have much effect. This depends on your specific platform and VM implementation:)--//from "Think in Java"

Keyword synchronized is provided in Java to provide built-in support for preventing resource conflicts. When used to modify a method or block of code, it is guaranteed that at most one thread at a time the method or block of code can be accessed at most. about synchronized used for methods, for code blocks, for static methods to refer to the use of synchronized in the blog Java

sychronized (This) is understood :

This refers to the object that called the method, such as P1. The visible synchronization method is essentially the synchronized action on object reference.  =.= that get the P1 object lock thread, can call P1 synchronization method, and for P2, P1 this lock and it is irrelevant, the program may in this case get rid of synchronization mechanism control, resulting in data confusion:) Use three examples to enhance your understanding of:

Example One :


Public classThread1ImplementsRunnable { Public voidrun () {synchronized( This) {// yoke for(inti = 0; I < 5; i++) {System.out.println (Thread.CurrentThread (). GetName ()+ "Synchronized loop" +i);
try {
Thread.Sleep (1000);
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
} } } } Public Static voidMain (string[] args) {Thread1 T1=NewThread1 (); Thread Ta=NewThread (T1, "A"); Thread TB=NewThread (T1, "B"); A thread executes first, then executes B thread Ta.start (); Tb.start (); }}

Results :
A Synchronized Loop 0
A Synchronized Loop 1
A Synchronized Loop 2
A Synchronized Loop 3
A Synchronized Loop 4
B Synchronized Loop 0
B Synchronized Loop 1
B Synchronized Loop 2
B Synchronized Loop 3
B Synchronized Loop 4

Example two:

 Public classThread2 { Public voidm4t1 () {synchronized( This) {// Yoke 1 inti = 5;  while(i--> 0) {System.out. println (Thread.CurrentThread (). GetName ()+ " : " +i); Try{Thread.Sleep (500); } Catch(Interruptedexception IE) {}}} }     Public voidm4t2 () {synchronized( This) {// Yoke 2 inti = 5;  while(i--> 0) {System.out. println (Thread.CurrentThread (). GetName ()+ " : " +i); Try{Thread.Sleep (300);// hibernate short }Catch(Interruptedexception IE) {}}} }     Public Static voidMain (string[] args) {FinalThread2 myt2 =NewThread2 (); Thread T1=NewThread (NewRunnable () { Public voidrun () {myt2.m4t1 ();/a thread only calls the yoke of M4T1 (), the B thread calls the yoke of the M4T2 (), still needs to wait for a to finish }}, A); Thread T2=NewThread (NewRunnable () { Public voidrun () {myt2.m4t2 (); }        }, B);        T1.start ();    T2.start (); }}

Results :

A:4
A:3
A:2
A:1
a:0
B:4
B:3
B:2
B:1
b:0
That is, when a thread accesses a synchronized (this) of object to synchronize a block of code, it obtains 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.

example Three :

 Public classThread3 { Public voidm4t1 () {synchronized( This) {//Yokeinti = 5;  while(i--> 0) {System.out. println (Thread.CurrentThread (). GetName ()+ " : " +i); Try{Thread.Sleep (500); } Catch(Interruptedexception IE) {}}} }     Public voidm4t2 () {inti = 5;//Not Shackles while(i--> 0) {System.out. println (Thread.CurrentThread (). GetName ()+ " : " +i); Try{Thread.Sleep (300); } Catch(Interruptedexception IE) {}}}  Public Static voidMain (string[] args) {FinalThread3 MYT3 =NewThread3 (); Thread T1=NewThread (NewRunnable () { Public voidrun () {myt3.m4t1 ();//}},A); Thread T2=NewThread (NewRunnable () { Public voidrun () {myt3.m4t2 (); }        }, B);        T1.start ();    T2.start (); }}

result : (with uncertainty)

A:4
B:4
B:3
A:3
B:2
B:1
A:2
b:0
A:1
a:0
When a thread accesses one of the synchronized (this) synchronization blocks of object, another thread can still access the non-synchronized (this) synchronous block of code in the object.

Summary: All objects have a single lock (also a monitor). When an arbitrary synchronized method is called on an object, the object is locked, and the other synchronized method on the object is called before it can be called until the previous method call is complete and released.

Note: When using concurrency, it is important to set the domain to private. Otherwise, the Synchronized keyword does not prevent other tasks from accessing the domain directly, which creates a conflict.

One more thing:

  A task can obtain the lock of an object multiple times, and if a method invokes a second method on the same object, which invokes another method on the same object, this can happen. The JVM is responsible for tracking the number of times an object is locked. If an object is fully unlocked, its count becomes 0. Whenever a task leaves a synchronized method, the Count decrements, and when the count is 0, the lock is completely freed, and the resource is available for other tasks at this time:)

For each class, there is also a lock (as part of the class object), so the synchronized static method can prevent concurrent access to the static data in the class's scope class.

Java synchronized use

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.