synchronized锁重入:就是一个对象中存在多个同步方法,当一个同步方法调用的另外一个同步方法的时候,不需要再去竞争锁,因为该线程已经拥有了该对象的锁,父子类同样也支持锁重入,我们看下具体代码:
package com.ck.thread;
public class Father {
public synchronized void eat() {
System.out.println("吃饭");
xiwan();
System.out.println("吃饭整个过程结束");
}
public synchronized void xiwan() {
System.out.println("洗碗");
}
}
就是父类在吃完饭以后,需要洗碗,洗完碗以后吃饭才算结束,我们看下吃的线程:
package com.ck.thread;
public class EatThread extends Thread{
private Father father;
public EatThread(Father father) {
super();
this.father = father;
}
public Father getFather() {
return father;
}
public void setFather(Father father) {
this.father = father;
}
@Override
public void run() {
father.eat();
}
}
我们再看下主线程:
package com.ck.thread;
public class MainThread {
public static void main(String[] args) throws InterruptedException {
Father father = new Father();
EatThread eatThread = new EatThread(father);
eatThread.start();
}
}
我们看下运行结果:
吃饭
洗碗
吃饭整个过程结束
通过上面例子我们可以看到eat方法再一次调用xiwan方法的时候,可以直接调用,不需要等待,这就是synchronized锁重入 ,下一篇我们会继续讲父子类锁重入。