SynClass.java
public class SynClass {
// 用以测试方法对象锁锁定的对象是
public void run() {
synchronized (this) {
try {
System.out.println("ok");
Thread.sleep(100000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// 用于锁定 class,测试静态方法锁
public static void lockedClass() {
synchronized (SynClass.class) {
try {
System.out.println(Thread.currentThread() + "\tlockedClass");
Thread.sleep(300000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("lockedClass End");
}
}
// 静态方法锁
public static synchronized void clsPrint1() {
System.out.println(Thread.currentThread() + "\tclsPrint1");
try {
Thread.sleep(300000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static synchronized void clsPrint2() {
System.out.println(Thread.currentThread() + "\tclsPrint1");
try {
Thread.sleep(300000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 对象方法锁
public synchronized void objPrint1() {
System.out.println(Thread.currentThread() + "\tprint1");
try {
Thread.sleep(300000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void objPrint2() {
System.out.println(Thread.currentThread() + "\tprint1");
try {
Thread.sleep(300000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void objPrint3() {
System.out.println(Thread.currentThread() + "\tprint1");
try {
Thread.sleep(300000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Synchronized.java
public class Synchronized {
public static void main(String[] args) throws Exception {
// 同一对象方法级锁 // 阻塞
// 1、先执行run,后边均阻塞。因为run方法锁定了当前对象,后续方法阻塞说明方法的锁是加在对象上的
// 2、注释run,后两个被阻塞
// SynClass sc = new SynClass();
// new Thread(() -> sc.run()).start(); Thread.sleep(1000);
// new Thread(() -> sc.objPrint1()).start(); Thread.sleep(1000);
// new Thread(() -> sc.objPrint2()).start(); Thread.sleep(1000);
// new Thread(() -> sc.objPrint3()).start(); Thread.sleep(1000);
// 静态方法锁 // 阻塞
// 1、先执行lockedclass,后两个阻塞。因为lockedclass方法锁定了SynClass类的Class对象,后续方法阻塞说明静态方法锁是加在类的Class上
// 2、注释lockedclass 第三个被阻塞
// new Thread(() -> SynClass.lockedClass()).start(); Thread.sleep(1000);
// new Thread(() -> SynClass.clsPrint1()).start(); Thread.sleep(1000);
// new Thread(() -> SynClass.clsPrint1()).start();
}
}