First, the synchronization method, whether it is the current object locked or the current class
Code Block 1
Package Com.ssss;public class Thread1 implements Runnable { //public static object O=new object (); public void Run () { pt (); } Public synchronized Void Pt () { int a=0; Synchronized (o) {for (int i = 0; i < 5; i++) { a++; try {thread.sleep;} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + "synchronized loop" + i + "++++" + a); } } } public static void Main (string[] args) { Thread1 t1 = new Thread1 (); Thread1 t2 = new Thread1 (); Thread ta = new Thread (T1, "A"); Thread TB = new Thread (t2, "B"); Ta.start (); Tb.start (); } }
The printed result is
This shows that the current object, and A and B are two different objects, so the print sequence is confusing
Code Block 2
Look at the sync block
Package Com.ssss;public class Thread1 implements Runnable {public static object O=new object (); public void Run () { pt (); } public void Pt () { int a=0; Synchronized (o) {for (int i = 0; i < 5; i++) { a++; try {thread.sleep;} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + "synchronized loop" + i + "++++" + a); }} public static void Main (string[] args) { Thread1 t1 = new Thread1 (); Thread1 t2 = new Thread1 (); Thread ta = new Thread (T1, "A"); Thread TB = new Thread (t2, "B"); Ta.start (); Tb.start (); } }
Look at the print sequence
Description Sync block can lock any object
That is, the synchronization method locks the current object, and the synchronous method block can lock any object
Java thread synchronization methods, method block differences