Java synchronized detailed

Source: Internet
Author: User

The Java language keyword that, when used to decorate a method or a block of code, guarantees that at most one thread executes the code at the same time.

  • 1. When two concurrent threads access the synchronized (this) synchronization code block in the same object, 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.
  • 2. When a thread accesses one synchronized (this) of object to synchronize a block of code, another thread can still access the non-synchronized (this) synchronous code block in the object.

3. In particular, when a thread accesses one of the synchronized (this) synchronization blocks of object, other threads will block access to all other synchronized (this) synchronous blocks of code in object.

4. The third example also applies to other synchronization code blocks. 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.

5. The above rules also apply to other object locks.

 Public classThread1ImplementsRunnable { Public voidrun () {synchronized( This) {                  for(inti = 0; I < 5; i++) {System.out.println (Thread.CurrentThread (). GetName ()+ "Synchronized loop" +i); }            }       }        Public Static voidMain (string[] args) {Thread1 T1=NewThread1 (); Thread Ta=NewThread (T1, "A"); Thread TB=NewThread (T1, "B");            Ta.start ();       Tb.start (); } }

Operation Result:

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

 Public classThread2 { Public voidm4t1 () {synchronized( This) {                 inti = 5;  while(i--> 0) {System.out.println (Thread.CurrentThread (). GetName ()+ ":" +i); Try{Thread.Sleep (500); } Catch(Interruptedexception IE) {}}} }        Public voidm4t2 () {inti = 5;  while(i--> 0) {System.out.println (Thread.CurrentThread (). GetName ()+ " : " +i); Try{Thread.Sleep (500); } Catch(Interruptedexception IE) {}}}  Public Static voidMain (string[] args) {FinalThread2 myt2 =NewThread2 (); Thread T1=NewThread (NewRunnable () { Public voidRun () {myt2.m4t1();}}, "T1"); Thread T2=NewThread (NewRunnable () { Public voidRun () {myt2.M4t2();}}, "T2");            T1.start ();       T2.start (); } }

Operation Result:

Results:
T1:4
T2:4
T1:3
T2:3
T1:2
T2:2
T1:1
T2:1
t1:0
t2:0

//To Modify the Thread2.m4t2 () method:      Public voidm4t2 () {synchronized( This) {                 inti = 5;  while(i--> 0) {System.out.println (Thread.CurrentThread (). GetName ()+ ":" +i); Try{Thread.Sleep (500); } Catch(Interruptedexception IE) {}}} }

Results:
T1:4
T1:3
T1:2
T1:1
t1:0
T2:4
T2:3
T2:2
T2:1
t2:0

Using object locks:

 Public classFooextendsThread {Private intVal; PrivateString name; Privateobject lock; PublicFoo (String N,intV, Object L) {Val=v; Name=N; Lock=l; }     Public voidPrintval ()throwsinterruptedexception {synchronized(lock) { while(val>0) {Thread.Sleep (500); SYSTEM.OUT.PRINTLN (Name+ " " +val); Val--; }        }    }     Public voidrun () {Try{printval (); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }     Public Static voidMain (String args[]) {Object lock=NewString ("3"); Foo F1=NewFoo ("F1", 5, lock);        F1.start (); Foo F2=NewFoo ("F2", 5, "3"); F2.start ();    }}

Results:

F2:5
F1:5
F2:4
F1:4
F1:3
F2:3
F1:2
F2:2
F1:1
F2:1

If the lock is replaced by an object, as follows:

 Public Static void Main (String args[]) {        new Foo ("F1", 5, 2);        F1.start ();         New Foo ("F2", 5, 2);        F2.start ();         long mask = 0xFFL << 8;        SYSTEM.OUT.PRINTLN (mask);    }

Results:

F1:5
F1:4
F1:3
F1:2
F1:1
F2:5
F2:4
F2:3
F2:2
F2:1

Synchronized Method: Declare the Synchronized method by adding the Synchronized keyword to the method declaration. Such as:
Public synchronized void Accessval (int newval);
The Synchronized method Controls access to class member variables: Each class instance corresponds to a lock, and each synchronized method must obtain a lock on the class instance that invokes the method to execute, otherwise the owning thread is blocked, and once the method executes, the lock is exclusive until the lock is released from the method return , the blocked thread can then get the lock and re-enter the executable state. This mechanism ensures that at the same time for each class instance, at most one of its member functions declared as synchronized is in an executable state.

synchronized block: declares the synchronized block with the Synchronized keyword. The syntax is as follows:
Synchronized (SyncObject) {
Code that allows access control
}
The synchronized block is a block of code in which the code must obtain an object SyncObject (as previously described, which can be a class instance or Class) to execute, as described in the previous mechanism. Because it can be arbitrary code block, and can arbitrarily specify the locked object, it is more flexible.

Synchronized Method: You can think that the whole method of the content is put in the synchronized (this) {} in block

The interesting code is as follows:

 Public classFooextendsThread {Private intVal; PrivateString name; PrivateObject Lock; Private intVal2;  Public voidSetvalues (String N,intV, Object L) {Val=v; Name=N; Lock=l; Val2= 0-v; }    Private voidsleep () {Try{Thread.Sleep (500); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }     PublicFoo () {} PublicFoo (String N,intV, Object L) {Val=v; Name=N; Lock=l; Val2= 0-v; }     Public voidPrintval () {synchronized(lock) { while(val>0) {System.out.println (name+ ": " +val); Val--;            Sleep (); }        }    }         Public synchronized voidPrintVal2 () { while(Val2 < 0) {System.out.println (name+ ": " +val2); Val2++;        Sleep (); }    }     Public voidrun () {printval (); }     Public Static voidMain (String args[]) {FinalFoo F1 =NewFoo (); F1.setvalues ("F1", 5, F1); FinalFoo F2 =NewFoo ("F2", 5, F1); Thread T1=NewThread (NewRunnable () { Public voidrun () {f1.printval2 ();        }        }); Thread T2=NewThread (NewRunnable () { Public voidrun () {f2.printval2 ();        }        }); F1.start (); //lock = F1F2.start ();//lock = F1T1.start ();//lock = F1T2.start ();//lock = F2    }}

Output:

F1:5
F2:-5
F2:-4
F1:4
F1:3
F2:-3
F2:-2
F1:2
F2:-1
F1:1
F2:5
F2:4
F2:3
F2:2
F2:1
F1:-5
F1:-4
F1:-3
F1:-2
F1:-1

Java synchronized detailed

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.