The understanding of synchronize keywords in Java is applied in multithreaded environments: The Synchronized keyword, which includes two usages: Synchronized method and synchronized block. 1. Syn

Source: Internet
Author: User
Tags object object thread class

The understanding of synchronize keywords in Java is applied in multithreaded environment:

Synchronized keyword, which includes two usages: Synchronized method and synchronized block.

1. Synchronized method: Declare the Synchronized method by adding the Synchronized keyword to the method declaration. Such as:

Public synchronized void Accessval (Intnewval);

The Synchronized method Controls access to class member variables: Each class instance corresponds to a lock, each synchronized method must obtain a lock that invokes the class instance of the method to execute, otherwise the owning thread is blocked, and once the method is executed, the lock is exclusive until the lock is released when the method returns , 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 only one of the member functions declared as synchronized is in the executable state (since at most one can obtain the lock of that class instance), This effectively avoids the access violation of class member variables (as long as all possible methods of accessing class member variables are declared as synchronized).

In Java, not just the class instance, each class also corresponds to a lock, so we can also declare the static member function of the class as synchronized to control its access to the static member variables of the class.

The flaw of the Synchronized method: If a large method is declared as synchronized, it will greatly affect efficiency, typically, if the thread class method run () is declared as synchronized, because it is running throughout its lifetime, Therefore, the invocation of any synchronized method in this class will never succeed. Of course, we can do this by putting the code that accesses the class member variable into a specialized method, declaring it as synchronized, and tuning it in the main method to solve the problem, but Java provides us with a better solution, which is the synchronized block.

2. Synchronized BLOCK: Declare synchronized block by synchronized keyword. The syntax is as follows:

Synchronized (SyncObject) {

Code that allows access control

}

A synchronized block is a block of code in which the code must obtain the lock of the object SyncObject (as described previously, can be a class instance or Class), and the specific mechanism is described in the previous instance. Because you can target arbitrary blocks of code, and can arbitrarily specify locked objects, so flexibility is high.

Some understanding of synchronized (this) (very meticulous, thanks to the author.) )

First, when two concurrent threads access the synchronized (this) synchronized code block in the same object objects, only one thread can be executed at a time. Another thread must wait until the current thread finishes executing the code block before executing the code block.

Second, however, when a thread accesses a synchronized (this) synchronization code block of object, another thread can still access a non-synchronized (this) synchronized code block in that object.

Third, it is particularly critical that when a thread accesses a synchronized (this) synchronization code block of object, access to all other synchronized (this) synchronized code blocks in object is blocked by other threads.

The third example also applies to other synchronized code blocks. That is, when a thread accesses a synchronized (this) synchronization code block of object, it obtains the object lock of the objects. As a result, access to all of the synchronization code portions of the object object by other threads is temporarily blocked.

The above rules apply to other object locks as well.

An example is provided:

First, when two concurrent threads access the synchronized (this) synchronized code block in the same object objects, only one thread can be executed at a time. Another thread must wait until the current thread finishes executing the code block before executing the code block.

package ths;

public class Thread1 implements Runnable {

public void Run () {

Synchronized (this) {

for (int i = 0; i < 5; i++) {

System.out.println (Thread.CurrentThread (). GetName () + "synchronized loop" + i);

}

}

}

public static void Main (string[] args) {

Thread1 T1 = new Thread1 ();

Thread ta = new Thread (T1, "A");

Thread TB = new Thread (T1, "B");

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

Second, however, when a thread accesses a synchronized (this) synchronization code block of object, another thread can still access a non-synchronized (this) synchronized code block in that object.

package ths;

public class Thread2 {

public void M4t1 () {

Synchronized (this) {

int i = 5;

while (i--> 0) {

System.out.println (Thread.CurrentThread (). GetName () + ":" + i);

try {

Thread.Sleep (500);

catch (Interruptedexception IE) {

}

}

}

}

public void M4t2 () {

int i = 5;

while (i--> 0) {

System.out.println (Thread.CurrentThread (). GetName () + ":" + i);

try {

Thread.Sleep (500);

catch (Interruptedexception IE) {

}

}

}

public static void Main (string[] args) {

Final Thread2 myt2 = new Thread2 ();

thread T1 = new Thread (

New Runnable () {

public void Run () {

Myt2.m4t1 ();

}

}, "T1"

);

Thread t2 = new Thread (

New Runnable () {

public void Run () {

Myt2.m4t2 ();

}

}, "T2"

);

T1.start ();

T2.start ();

}

}

Results:

T1:4

T2:4

T1:3

T2:3

T1:2

T2:2

T1:1

T2:1

t1:0

t2:0

Third, it is particularly critical that when a thread accesses a synchronized (this) synchronization code block of object, access to all other synchronized (this) synchronized code blocks in object is blocked by other threads.

To modify the Thread2.m4t2 () method:

public void M4t2 () {

Synchronized (this) {

int i = 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

The third example also applies to other synchronized code blocks. That is, when a thread accesses a synchronized (this) synchronization code block of object, it obtains the object lock of the objects. As a result, access to all of the synchronization code portions of the object object by other threads is temporarily blocked.

Modify the Thread2.m4t2 () method as follows:

Public synchronized void M4t2 () {

int i = 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

The above rules apply to other object locks as well:

package ths;

public class Thread3 {

Class Inner {

private void M4t1 () {

int i = 5;

while (i--> 0) {

System.out.println (Thread.CurrentThread (). GetName () + ": inner.m4t1 () =" + i);

try {

Thread.Sleep (500);

catch (Interruptedexception IE) {

}

}

}

private void M4t2 () {

int i = 5;

while (i--> 0) {

System.out.println (Thread.CurrentThread (). GetName () + ": inner.m4t2 () =" + i);

try {

Thread.Sleep (500);

catch (Interruptedexception IE) {

}

}

}

}

private void M4t1 (Inner Inner) {

Synchronized (inner) {//Use object lock

Inner.m4t1 ();

}

}

private void M4t2 (Inner Inner) {

Inner.m4t2 ();

}

public static void Main (string[] args) {

Final Thread3 myt3 = new Thread3 ();

Final Inner Inner = Myt3.new Inner ();

thread T1 = new Thread (

New Runnable () {

public void Run () {

MYT3.M4T1 (inner);

}

}, "T1"

);

Thread t2 = new Thread (

New Runnable () {

public void Run () {

MYT3.M4T2 (inner);

}

}, "T2"

);

T1.start ();

T2.start ();

}

}

Results:

Although thread T1 obtains an object lock on inner, thread T2 accesses the asynchronous part of the same inner. So two threads do not interfere with each other.

T1:INNER.M4T1 () =4

T2:Inner.m4t2 () =4

T1:INNER.M4T1 () =3

T2:Inner.m4t2 () =3

T1:INNER.M4T1 () =2

T2:Inner.m4t2 () =2

T1:INNER.M4T1 () =1

T2:Inner.m4t2 () =1

T1:INNER.M4T1 () =0

T2:Inner.m4t2 () =0

Now precede inner.m4t2 () with synchronized:

Private synchronized void M4t2 () {

int i = 5;

while (i--> 0) {

System.out.println (Thread.CurrentThread (). GetName () + ": inner.m4t2 () =" + i);

try {

Thread.Sleep (500);

catch (Interruptedexception IE) {

}

}

}

Results:

Although thread T1 and T2 access two unrelated parts of the same inner object, inner's access to T2 () is blocked because T1 first obtains an object lock on Inner.m4t2, because M4t2 () is a synchronous method in inner.

T1:INNER.M4T1 () =4

T1:INNER.M4T1 () =3

T1:INNER.M4T1 () =2

T1:INNER.M4T1 () =1

T1:INNER.M4T1 () =0

T2:Inner.m4t2 () =4

T2:Inner.m4t2 () =3

T2:Inner.m4t2 () =2

T2:Inner.m4t2 () =1

T2:Inner.m4t2 () =0

-----------------------------------------------------------------------------

2. Java thread and synchronization (synchronized) sample code

Import java.io.*;

Import java.util.*;

Import Java.text.SimpleDateFormat;

public class Testthread extends Thread

{

private static Integer threadcounterlock;//for synchronization to prevent data from being written in chaos

private static int threadcount; Thread counters for this class

Static

{

ThreadCount = 0;

Threadcounterlock = new Integer (0);

}

Public Testthread ()

{

Super ();

}

Public synchronized Static Voidincthreadcount ()

{

threadcount++;

SYSTEM.OUT.PRINTLN ("Thread count Afterenter:" + threadcount);

}

Public synchronized Static Voiddecthreadcount ()

{

threadcount--;

SYSTEM.OUT.PRINTLN ("Thread count Afterleave:" + threadcount);

}

public void Run ()

{

Synchronized (threadcounterlock)//Sync

{

threadcount++;

SYSTEM.OUT.PRINTLN ("Thread count Afterenter:" + threadcount);

}

Incthreadcount (); is equivalent to the statement block above.

Final long nsleepmillisecs = 1000; Sleep time in a loop

Long Ncurrenttime =system.currenttimemillis ();

Long Nendtime = Ncurrenttime + 30000; Run due time

SimpleDateFormat SimpleDateFormat = Newsimpledateformat ("Yyyy-mm-dd HH:mm:ss");

Try

{

while (Ncurrenttime < nendtime)

{

Ncurrenttime = System.currenttimemillis ();

System.out.println ("Thread" +this.hashcode () + ", Current time:" + Simpledateformat.format (newdate (Ncurrenttime)));

Try

{

Sleep (nsleepmillisecs);

}

catch (Interruptedexception ex)

{

Ex.printstacktrace ();

}

}

}

Finally

{

Synchronized (threadcounterlock)//Sync

{

threadcount--;

SYSTEM.OUT.PRINTLN ("Thread count Afterleave:" + threadcount);

}

Decthreadcount (); is equivalent to the statement block above.

}

}

public static void Main (string[] args)

{

testthread[] Testthread = newtestthread[2];

for (int i=0; i{

Testthread[i] = new Testthread ();

Testthread[i].start ();

}

}

}

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.