public void methodC(){
Object obj = new Object();
synchronized(obj){
for(int i=0; i<5; i++){
System.out.println(Thread.currentThread().getName()+"方法"+i);
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
在上述代码中Object每次代表的值不同,每次上的锁也不同。
public void methodC(){
static Object obj = new Object();
synchronized(obj){
for(int i=0; i<5; i++){
System.out.println(Thread.currentThread().getName()+"方法"+i);
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
由于object是静态的,所有object都是同一把锁,根据业务来决定用什么。