package test;
public class LockExer {
private static String lockA="locka";
private static String lockB="lockb";
public void methodA() throws Exception {
synchronized (lockA){
System.out.println("我是A方法获取锁A:"+Thread.currentThread().getName());
// 让出CPU执行权,但是不释放锁
Thread.sleep(1000);
synchronized (lockB){
System.out.println("我是A方法获取锁B:"+Thread.currentThread().getName());
}
}
}
public void methodB() throws Exception {
synchronized (lockB){
System.out.println("我是B方法获取锁B:"+Thread.currentThread().getName());
// 让出CPU执行权,但是不释放锁
Thread.sleep(1000);
synchronized (lockA){
System.out.println("我是B方法获取锁A:"+Thread.currentThread().getName());
}
}
}
public static void main(String[] args) {
LockExer lockExer = new LockExer();
new Thread(()->{
try {
lockExer.methodA();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
new Thread(()->{
try {
lockExer.methodB();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
System.out.println("执行完成");
}
}