synchronized-锁重入

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();

                }
            }
        }
    }
    public static void main(String[] args) {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                Sub s = new Sub();
                s.operationSub();
            }
        });
        t.start();
    }
}

描述:

  关键字 synchronized 拥有锁重入的功能, 也就是使用 synchronized 的时候,当一个线程得到一个对象的锁后,再次请求此对象是是可以再次得到该对象的锁。

运行结果:

原文地址:https://www.cnblogs.com/xxt19970908/p/6965294.html