Java keyword synchronized

Source: Internet
Author: User

1, for synchronized method and synchronized block, when one thread accesses, other threads can access the non-synchronized method or block of this class, and cannot access other methods or blocks with synchronized.

Examples are as follows:

Synchronized Block:

public class Thread2 {

public void M4t1 () {
Synchronized (this) {
int i = 5;
while (i--> 0) {
System.out.println (Thread.CurrentThread (). GetName () + ":" + i);
try {
Thread.Sleep (2000);
} catch (Interruptedexception IE) {
Ie.printstacktrace ();
}
}
}
}

public void M4t2 () {
Synchronized (this) {
int i = 5;
while (i--> 0) {
System.out.println (Thread.CurrentThread (). GetName () + ":" + i);
try {
Thread.Sleep (2000);
} catch (Interruptedexception IE) {
Ie.printstacktrace ();
}
}
}
}

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 ();
}
}

Synchronized method:

public class Thread3 {

Public synchronized void M4t1 () {

int i = 5;
while (i--> 0) {
System.out.println (Thread.CurrentThread (). GetName () + ":" + i);
try {
Thread.Sleep (2000);
} catch (Interruptedexception IE) {
Ie.printstacktrace ();
}
}

}

Public synchronized void M4t2 () {

int i = 5;
while (i--> 0) {
System.out.println (Thread.CurrentThread (). GetName () + ":" + i);
try {
Thread.Sleep (2000);
} catch (Interruptedexception IE) {
Ie.printstacktrace ();
}
}

}

public static void Main (string[] args) {
Final Thread3 myt2 = new Thread3 ();
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 ();
}

Java keyword synchronized

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.