1.synchronized 修饰方法
相当于给该实例对象加锁,该对象中所有被synchronized修饰的方法,都要等对象锁释放
如:
class A {
public synchronized void method1(){}
public synchronized void method2(){}
}
public static void main(String[] args){
A a=new A();
a.method1;
a.method2;(要等method1执行完才会执行method2,因为a对象被锁)
A b=new A();
a.method1;
b.method2;(不用等method1执行完,会并发执行method2,因为是两个对象,互相不影响)
}
2. static synchronized 修饰方法
相当于给该类加锁,该类中所有被 static synchronized修饰的方法,都要等类释放
如:
class A{
public static synchronized void method1(){}
public static synchronized void method2(){}
}
public static void main(String[] args){
A a=new A();
A b=new A();
a.method1;
b.method2;(要等method1执行完才会执行method2,因为A类被锁)
}
3.static syncronized 修饰的方法和 syncronized修饰的方法,互相不想影响,会并发执行
如:
class A{
public synchronized void method1(){}
public static synchronized void method2(){}
}
public static void main(String[] args){
A a=new A();
a.method1;
a.method2;(不用等method1执行完,会并发执行method2,互相不想影响)
}
4.syncronized 代码块class {
String a
public void method1(){
syncronized (a){}
}
public void method2(){
syncronized (a){}
}
}
public static void main(String[] args){
a.method1;
a.method2;(要等method1执行完才会执行method2,因为a变量被锁)
}