package demo1;
/**
* synchronized锁重入
* Created by liudan on 2017/6/5.
*/
public class MyThread5_synchronized1 {
/**
* 父子类同步必须 都 使用synchronized关键字
*/
static class Main {
public int count = 10;
public synchronized void operationSub() {
try {
count--;
System.err.println("Main print count = " + count);
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
static class Sub extends Main {
public synchronized void operationSub() {
while (count > 0) {
try {
count--;
System.err.println("Sub print count = " + count);
Thread.sleep(100);
super.operationSub();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* 关键字 synchronized 拥有锁重入的功能, 也就是使用 synchronized 的时候,当一个线程得到一个对象的锁后,再次请求此对象
* 是是可以再次得到该对象的锁。
*/
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
Sub s = new Sub();
s.operationSub();
}
});
t.start();
}
}