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