2.1.6锁重入(支持继承锁)

来源:互联网 发布:知轩藏书网 编辑:程序博客网 时间:2024/06/08 04:41

某个线程获得了锁,这个锁没有释放之前,再次想要获取对象锁的时候,还是可以获取的。即,一个synchronized方法内部调用另外一个带synchronized的方法,是同一个对象锁。

package cha02.execise07;/** * Created by sunyifeng on 17/9/24. */public 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");//    }}
package cha02.execise07;/** * Created by sunyifeng on 17/9/24. */public class MyThread extends Thread {    @Override    public void run(){        Service service = new Service();        service.service1();    }}
package cha02.execise07;/** * Created by sunyifeng on 17/9/24. */public class Run {    public static void main(String[] args) {        MyThread myThread = new MyThread();        myThread.start();    }}
运行结果:

service1
service2
service3

重入锁支持在父子继承的环境中。

package cha02.execise08;/** * Created by sunyifeng on 17/9/24. */public class Father {    public int i = 10;    synchronized public void operateFatherMethod() {        try {            i--;            System.out.println("father print i=" + i);            Thread.sleep(100);        } catch (InterruptedException e) {            e.printStackTrace();        }    }}
package cha02.execise08;/** * Created by sunyifeng on 17/9/24. */public class Child extends Father {    synchronized public void operateChildMethod() {        try {            while (i > 0) { // i是从父类继承的                i--;                System.out.println("child print i=" + i);                Thread.sleep(100);                this.operateFatherMethod();            }        } catch (InterruptedException e) {            e.printStackTrace();        }    }}
package cha02.execise08;/** * Created by sunyifeng on 17/9/24. */public class MyThread extends Thread {    @Override    public void run(){        Child child = new Child();        child.operateChildMethod();    }}
package cha02.execise08;/** * Created by sunyifeng on 17/9/24. */public class Run {    public static void main(String[] args) {        MyThread myThread = new MyThread();        myThread.start();    }}
运行结果:

child print i=9
father print i=8
child print i=7
father print i=6
child print i=5
father print i=4
child print i=3
father print i=2
child print i=1
father print i=0

程序分析:

父类方法、子类方法都加了同步锁,子类方法调用父类的方法,子类和父类都操作变量i(自减--)。

原创粉丝点击