锁的重入
package demo;
/*
* synchronized的重入
* 关键字synchronized拥有锁重入得功能,
* 当一个线程得到了一个对象的锁后,再次请求次对象时时可以再次得到该对象的锁。
*
*
*
* */
public class MyDubbo {
//在synchronized 方法一种调用synchronized 方法2,
//方法2中又调用方法3
public synchronized void method1(){
System.out.println("method1....");
method2();
}
public synchronized void method2(){
System.out.println("method2....");
method3();
}
public synchronized void method3(){
System.out.println("method3....");
}
public static void main(String[] args) {
final MyDubbo my1 = new MyDubbo();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
my1.method1();
}
});
//synchronized的重入 表面上看是三个方法都synchronized,以为要method1执行获取锁对象后,
//执行完毕后,method2才能获取锁对象。事实不是这样的,synchronized重入
//将三个方法的synchronized都去掉,结果一样,但是机制不一样。
t1.start();
}
}
AI 代码解读
子父类的重入
package demo;
/*
* 子类父类之间的重入是可行的。
*
* 重入得异常的捕捉。一定要考虑整体问题,处理异常。
* */
public class MyDubbo2 {
static class Main{
public int num = 10 ;
public synchronized void operationMainSup(){
try {
num--;
System.out.println("Main print num = " + num );
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
static class Sub extends Main{
public synchronized void operationSubSup() {
try {
while(num>0){
num--;
System.out.println("Sub print num = " + num );
Thread.sleep(100);
//父类中的方法
this.operationMainSup();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
Sub sub = new Sub();
sub.operationSubSup();
}
});
//开始线程
t1.start();
}
}
AI 代码解读