Synchronized可重入性解释:
自己可以再次获取自己的内部锁。
Public class Service{
Synchronized public void service1(){
System.out.println(“service1”);
Service2();
}
Synchronized public void service2(){
System.out.println(“service2”);
Serice3();
}
Synchronized public void service3(){
System.out.println(“service3”);
}
}
通过调用Service.service1()方法可以直接输出
Service1
Service2
Service3
另外可重入锁也可以在继承父类的子类中使用
Main:
public class Main {
public int i=10;
synchronized public void operateMainMethod() {
try {
i--;
System.out.println("main print i="+i);
Thread.sleep(100);
} catch (Exception e) {
// TODO: handle exception
}
}
}
Sub:
public class Sub extends Main {
synchronized public void operateISubMethod() {
try {
while(i>0) {
i--;
System.out.println("sub print i="+i);
Thread.sleep(100);
this.operateMainMethod();
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
MyThread:
public class MyThread extends Thread{
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
Sub sub=new Sub();
sub.operateISubMethod();
}
}
Run:
public class Run {
public static void main(String[] args) {
MyThread thread=new MyThread();
thread.start();
}
}