概念:自己可以获得自己的内部锁,比如一条线程获得某个对象的锁,此时这个对象锁还没有释放,当期再次想要获得这个对象锁的时候,还是可以获得的,如果不可重入锁则很有可能死锁
public class KechongruSyn {
public static void main(String[] args) {
myThread t=new myThread();
t.start();
}
}
class service{
synchronized public void service1(){
System.out.println("service1");
service2();
}
synchronized public void service2(){
System.out.println("service2");
service3();
}
synchronized public void service3(){
System.out.println("service3");
//service1();
}
}
class myThread extends Thread{
@Override
public void run() {
super.run();
service ser=new service();
ser.service1();
}
}
可重入锁支持子类继承父类的情形,
注意:子类完全可以通过可重入锁调用父类方法
代码实例:
public class KechongruSyn {
public static void main(String[] args) {
myThread t=new myThread();
t.start();
}
}
class service extends Father{
synchronized public void service1(){
System.out.println("service1");
// for(int i=0;i<10;i++){
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// System.out.println("还剩"+(9-i)+"s就执行");
// }
service2();
}
synchronized public void service2(){
System.out.println("service2");
service3();
}
synchronized public void service3(){
System.out.println("service3");
//service1();
}
}
class Father{
synchronized public void fatherMether(){
System.out.println("我是父类");
}
}
class myThread extends Thread{
@Override
public void run() {
super.run();
service ser=new service();
ser.service1();
ser.fatherMether();
}
}
执行结果:
service1
service2
service3
我是父类