对对象加锁的时候,哪些对象是在同步方法中
有两个对象都要被加锁
线程1先对A加锁,再对B加锁
线程2先对B加锁,再对A加锁
可能发生死锁
public class Main {
public static void main(String[] args) {
Object a = new Object();
Object b = new Object();
new ThreadLockTest(a,b,1).start();
new ThreadLockTest(a,b,2).start();
}
public static class ThreadLockTest extends Thread{
private Object a, b;
private Integer type;
public ThreadLockTest(Object a,Object b,Integer type){
this.a = a ;
this.b = b;
this.type = type;
}
public void run(){
while(true){
if(type == 1){
synchronized(a){
System.out.println(this.getName()+"对a加同步");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(b){
System.out.println(this.getName()+"对b同步");
}
}
}else{
synchronized(b){
System.out.println(this.getName()+"对b加同步");
synchronized(a){
System.out.println(this.getName()+"对a同步");
}
}
}
}
}
}
}