Java thread synchronization method, method block difference, java thread synchronization difference
First, let's talk about the synchronization method. Is it the locked current object 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(1000);} 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
It can be seen that it is the current object, while A and B are two different objects, so the print sequence is messy.
Code Block 2
View synchronization Blocks
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(1000);} 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(); } }
View print Sequence
It indicates that the synchronization block can lock any object.
That is to say, the synchronization method is to lock the current object, and the synchronization method block can lock any object.