package Synchronize;
class ShareObject1{}
class ShareObject2{}
class Thread1 extends Thread{
public void run(){
synchronized (ShareObject1.class){
System.out.println("线程1获取到ShareObject1锁");
try{
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
}
synchronized (ShareObject2.class){
System.out.println("线程1获取到ShareObject2锁");
}
}
}
class Thread2 extends Thread{
public void run(){
synchronized (ShareObject2.class){
System.out.println("线程2获取到ShareObject2锁");
try{
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
}
synchronized (ShareObject1.class){
System.out.println("线程2获取到ShareObject1锁");
}
}
}
public class Test034 {
public static void main(String[] args){
new Thread1().start();
new Thread2().start();
}
}
/**
* 上面的代码是会发生死锁的,因为线程1首先获取S1的锁,然后再去获取S2的锁,这个时候线程2已经拿着S2的锁,去获取S1的锁,这样就互相等待对象放锁,造成了死锁
* 解决方法:就是获取锁的顺序都一样,同时过去S1锁或者是去同时去获取S2锁---比如将线程2中的同步顺序换一下
* */